﻿if (typeof XMLHttpRequest == 'undefined') {
    XMLHttpRequest = function () {
        try {
            return new ActiveXObject('Msxml2.XMLHTTP.6.0');
        } catch (e) {}
        try {
            return new ActiveXObject('Msxml2.XMLHTTP.3.0');
        } catch (e) {}
        try {
            return new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {}
        try {
            return new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
        throw new Error('This browser does not support XMLHttpRequest.');
    };
}

function tilib_Template(template) {
    var _ta;
    if (template !== undefined) {
        _ta = _parse(template);
    } else {
        _ta = arguments[1];
    }

    function _parse(template) {
        var a = template.split('_{');
        var ac = a.length;
        for (var i = 1; i < ac; i++) {
            a[i] = a[i].split('}_');
        }
        return a;
    }
    this.getText = function (data) {
        if (data) {
            return _replace(data).join('');
        } else {
            return _replace().join('');
        }
    };

    function _replace(data) {
        var t = _ta;
        var tc = t.length;
        var ti;
        var a = [];
        a.push(t[0]);
        ti = 1;
        while (ti < tc) {
            var d = t[ti++];
            var key = d[0];
            if (data) {
                var value = data[key];
                if (value !== undefined) {
                    a.push(value);
                }
            }
            a.push(d[1]);
        }
        return a;
    }
    this.getTemplate = function (data) {
        var a = [];
        var text = [];
        var two = null;
        var t = _ta;
        var tc = t.length;
        text.push(t[0]);
        var ti = 1;
        while (ti < tc) {
            var d = t[ti++];
            var key = d[0];
            var value = data[key];
            if (value === undefined) {
                if (two === null) {
                    a.push(text.join(''));
                } else {
                    two[1] = text.join('');
                    a.push(two);
                }
                two = [key];
                text = [d[1]];
            } else {
                text.push(value);
                text.push(d[1]);
            }
        }
        if (two) {
            two[1] = text.join('');
            a.push(two);
        }
        return new tilib_Template(undefined, a);
    };
}

function tilib_GetOptionTemplate(base, override, name) {
    return new tilib_Template((override && override[name]) ? override[name] : base[name]);
}

function tilib_GenerateTemplates(templates) {
    var ts = {};
    for (key in templates) {
        ts[key] = new tilib_Template(templates[key]);
    }
    return ts;
}

function tilib_Token(names, values) {
    var _names = names;
    var _values = values;

    function _getIndex(name) {
        var c = _names.length;
        for (var i = 0; i < c; ++i) {
            if (name == _names[i]) {
                return i;
            }
        }
        return -1;
    }
    this.getToken = function () {
        return _values.join(',');
    };
    this.getValue = function (name) {
        var index = _getIndex(name);
        if (index >= 0) {
            return _values[index];
        } else {
            return undefined;
        }
    };
    this.setValue = function (name, value) {
        var index = _getIndex(name);
        if (index >= 0) {
            var v = _values[index];
            _values[index] = value;
            return v;
        } else {
            return undefined;
        }
    };
    this.clone = function () {
        return new tilib_Token(_names.slice(0), _values.slice(0));
    };
}

function tilib_GetBrowserVersion() {
    var ua = navigator.userAgent;
    if (ua.indexOf('MSIE') >= 0) {
        var re = new RegExp('MSIE ([0-9]{1,}[\.0-9]{0,})');
        if (re.exec(ua) != null) {
            return ['ie', parseFloat(RegExp.$1)];
        }
    }
    return null;
}

function tilib_UpdateCache(cache, data) {
    if (!data) return cache;
    if (!cache) return data;
    cache = cache.slice(0);
    var c = data.length;
    for (var i = 0; i < c; ++i) {
        var d = data[i];
        if (d != undefined) {
            if (typeof (d) == 'object') {
                if (d.length) {
                    cache[i] = tilib_UpdateCache(cache[i], d);
                } else {
                    cache[i] = d;
                }
            } else {
                cache[i] = data[i];
            }
        }
    }
    return cache;
}

function tilib_PopUp(name, url, o) {
    var p = [];
    var tb, sb, loc, stb, mb, res, w, h, l, t;
    tb = o['tb'] ? o['tb'] : 'no';
    sb = o['sb'] ? o['sb'] : 'yes';
    loc = o['loc'] ? o['loc'] : 0;
    stb = o['stb'] ? o['stb'] : 0;
    mb = o['mb'] ? o['mb'] : 0;
    res = o['res'] ? o['res'] : 'no';
    w = o['w'] ? o['w'] : 650;
    h = o['h'] ? o['h'] : 400;
    l = (screen.width / 2) - (w / 2);
    t = (screen.height / 2) - ((h + 75) / 2);
    p.push('toolbar=');
    p.push(tb);
    p.push(',scrollbars=');
    p.push(sb);
    p.push(',location=');
    p.push(loc);
    p.push(',statusbar=');
    p.push(stb);
    p.push(',menubar=');
    p.push(mb);
    p.push(',resizable=');
    p.push(res);
    p.push(',width=');
    p.push(w);
    p.push(',height=');
    p.push(h);
    p.push(',left=');
    p.push(l);
    p.push(',top=');
    p.push(t);
    var w = window.open(url, name, p.join(''));
    if (w) {
        if (w.blur) {
            w.blur();
        }
        if (w.focus) {
            w.focus();
        }
    }
    return w;
}

function tilib_Spinner(id) {
    var _this = this;
    var _targetId = id;
    var _target;
    var _requestComplete = false;
    var _timeoutComplete = false;
    var _spDiv;
    this.setTargetID = function (id) {
        _targetId = id;
    }
    this.requestEnded = function (flag) {
        if (!_spDiv) {
            return;
        }
        if (flag) {
            _requestComplete = true;
        } else {
            _timeoutComplete = true;
        }
        if (_requestComplete && _timeoutComplete) {
            _spDiv.style.display = 'none';
        }
    };
    this.requestStarted = function () {
        if (!_spDiv) {
            _spDiv = document.createElement('div');
            _spDiv.className = 'AjaxLoader';
            document.body.appendChild(_spDiv);
        }
        var w, h, l, t;
        _target = _targetId ? document.getElementById(_targetId) : undefined;
        if (_target) {
            var pos = tilib_FindPos(_target);
            w = _target.offsetWidth + 'px';
            h = _target.offsetHeight + 'px';
            l = pos[0] + 'px';
            t = pos[1] + 'px';
            _spDiv.style.position = 'absolute';
        } else {
            var dim = {
                w: 0,
                h: 0
            };
            tilib_GetWindowSize(dim);
            w = (dim.w) + 'px';
            h = (dim.h) + 'px';
            l = '0px';
            t = '0px';
            _spDiv.style.position = 'fixed';
        }
        _spDiv.style.width = w;
        _spDiv.style.height = h;
        _spDiv.style.left = l;
        _spDiv.style.top = t;
        setTimeout(function () {
            if (!_requestComplete) {
                _spDiv.style.display = 'block';
            }
        }, 250);
        _requestComplete = false;
        _timeoutComplete = false;
        setTimeout(function () {
            _this.requestEnded(false);
        }, 400);
    };
}

function tilib_GetWindowSize(s) {
    var winW = 0,
        winH = 0;
    if (document.body && document.body.offsetWidth) {
        winW = document.body.offsetWidth;
        winH = document.body.offsetHeight;
    }
    if (document.compatMode == 'CSS1Compat' && document.documentElement && document.documentElement.offsetWidth) {
        winW = document.documentElement.offsetWidth;
        winH = document.documentElement.offsetHeight;
    }
    if (window.innerWidth && window.innerHeight) {
        winW = window.innerWidth;
        winH = window.innerHeight;
    }
    s.w = winW;
    s.h = winH;
}

function tilib_Trim(s) {
    return s.replace(/^\s+|\s+$/g, '');
}

function tilib_InitHintTextbox(id, hint) {
    var tb = document.getElementById(id);
    if (!tb) {
        return;
    }
    tb.hintText = hint;
    tb.value = hint;
    tb.hasValue = false;
    tb.style.color = '#888';
    tb.onfocus = function () {
        if (tilib_Trim(tb.value) == tb.hintText && !tb.hasValue) {
            tb.value = "";
            tb.style.color = '#000';
        }
    };
    tb.onblur = function () {
        if (tilib_Trim(tb.value).length == 0) {
            tb.value = tb.hintText;
            tb.style.color = '#888';
            tb.hasValue = false;
        } else {
            tb.hasValue = true;
        }
    };
    tb.onent = function () {
        tb.hasValue = tilib_Trim(tb.value).length > 0;
    }
}

function tilib_InitTooltip(id, tid, h, c, ol, ot) {
    var _d = document.getElementById(id);
    var _t = document.getElementById(tid);
    var _ol = ol;
    var _ot = ot;
    if (!_d || !_t) {
        return;
    }
    _d.tipHeader = h;
    _d.tipContent = c;
    _d.tipDiv = _t;
    _d.headerTH = document.getElementById(tid + '-h');
    _d.contentTD = document.getElementById(tid + '-c');
    _d.onmouseover = function () {
        var pos = tilib_FindPos(_d);
        _d.headerTH.innerHTML = _d.tipHeader;
        _d.contentTD.innerHTML = _d.tipContent;
        _d.tipDiv.style.left = (pos[0] + _ol) + 'px';
        _d.tipDiv.style.top = (pos[1] + _ot) + 'px';
        _d.tipDiv.style.display = 'block';
        _d.className = 'InfoOver';
    };
    _d.onmouseout = function () {
        _d.tipDiv.style.display = 'none';
        _d.className = 'InfoUp';
    };
}

function tilib_FindPos(ele) {
    var curleft = curtop = 0;
    if (ele.offsetParent) {
        do {
            curleft += ele.offsetLeft;
            curtop += ele.offsetTop;
        } while ((ele = ele.offsetParent));
    }
    return [curleft, curtop];
}

function tilib_RemoveClassName(e, t) {
    var ec = ' ' + e.className.replace(/^s*|s*$/g, '') + ' ';
    var nc = ec;
    t = t.replace(/^s*|s*$/g, '');
    if (ec.indexOf(' ' + t + ' ') != -1) {
        nc = ec.replace(' ' + t.replace(/^s*|s*$/g, '') + ' ', ' ');
    }
    e.className = nc.replace(/^s*|s*$/g, '');
}

function tilib_ConvertNameToHTML(t) {
    var sb = [];
    var c = t.length;
    for (var i = 0; i < c; ++i) {
        var a = t.charAt(i);
        switch (a) {
        case '"':
            sb.push('&quot;');
            break;
        case '<':
            sb.push('&lt;');
            break;
        case '>':
            sb.push('&gt;');
            break;
        case '&':
            sb.push('&#38;');
            break;
        default:
            sb.push(a);
        }
    }
    return sb.join('');
}

function tilib_ConvertNameToCode(t) {
    var sb = [];
    if (t) {
        t = t.toLowerCase();
        var c = t.length;
        for (var i = 0; i < c; ++i) {
            var a = t.charAt(i);
            switch (a) {
            case ' ':
            case '_':
            case '$':
            case '&':
            case '+':
            case ',':
            case '/':
            case ':':
            case '=':
            case '?':
            case '@':
            case '\'':
            case '"':
            case '<':
            case '>':
            case '#':
            case '%':
                sb.push('-');
                break;
            default:
                sb.push(a);
            }
        }
    }
    return sb.join('');
}

function tilib_FixChromeTitle() {
    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
        window.resizeBy(1, 1);
        window.resizeBy(-1, -1);
    }
}

function tilib_CompareString(s1, s2) {
    var r = 0;
    if (s1 && s2) {
        s1 = s1 + '';
        s2 = s2 + '';
        var c = s1.length;
        if (s1.length > s2.length) {
            r = 1;
            c = s2.length;
        } else if (s1.length < s2.length) {
            r = -1;
        }
        for (var i = 0; i < c; ++i) {
            if (s1.charAt(i) > s2.charAt(i)) {
                r = 1;
                break;
            } else if (s1.charAt(i) < s2.charAt(i)) {
                r = -1;
                break;
            }
        }
    } else if (s1) {
        r = 1;
    } else if (s2) {
        r = -1;
    }
    return r;
}

function tilib_GetPriceString(pr) {
    var price = parseFloat(pr);
    var text = price.toFixed(3);
    if (text.charAt(text.length - 1) == '0') {
        return price.toFixed(2);
    }
    return text;
}

function tilib_CorrectFloat(value) {
    if (typeof (value) == 'number') {
        value = parseFloat(value.toFixed(6));
    }
    return value;
}

function tilib_RoundDown(value, digits) {
    value = parseFloat(value);
    if (typeof (value) == 'number') {
        var d = 1;
        for (var i = 0; i < digits; ++i) {
            d *= 10;
        }
        value = tilib_CorrectFloat(value);
        value = tilib_CorrectFloat(value * d);
        value = Math.floor(value);
        value = tilib_CorrectFloat(value / d);
    }
    return value;
}

function tilib_HasFlash() {
    if (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
        return true;
    } else {
        try {
            var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
            return true;
        } catch (e) {
            return false;
        }
    }
}

function tilib_RemoveElement(elemID) {
    var e = document.getElementById(elemID);
    if (e) {
        e.style.display = 'none';
        e.innerHTML = '';
    }
}

function tilib_GetQueryParams(w) {
    if (!w) w = window;
    var params = {};
    var index = w.location.href.indexOf('?');
    if (index > 0) {
        var query = w.location.href.substring(index + 1);
        var index = query.indexOf('#');
        if (index > 0) {
            query = query.substring(0, index);
        }
        var ps = query.split('&');
        var c = ps.length;
        var p;
        for (var i = 0; i < c; ++i) {
            p = ps[i];
            index = p.indexOf('=');
            params[p.substring(0, index)] = p.substring(index + 1);
        }
    }
    return params;
}

function tilib_AddClassItem(classValue, item) {
    var items = [];
    if (classValue) {
        var values = classValue.split(' ');
        for (var i = 0; i < values.length; ++i) {
            var value = values[i];
            if (value && value.length > 0) {
                items.push(value);
                if (value == item) {
                    item = null;
                }
            }
        }
    }
    if (item) {
        items.push(item);
    }
    return items.join(' ');
}

function tilib_RemoveClassItem(classValue, item) {
    var items = [];
    if (classValue) {
        var values = classValue.split(' ');
        for (var i = 0; i < values.length; ++i) {
            var value = values[i];
            if (value && value.length > 0 && value != item) {
                items.push(value);
            }
        }
    }
    return items.join(' ');
}

function __PageCache() {
    var _elements = {};
    this.getElement = function (n) {
        return _elements[n];
    };
    this.setElement = function (n, data, renew) {
        if (data) {
            var ces = _elements[n];
            if (!ces || renew) {
                _elements[n] = ces = {};
            }
            var dc = data.length;
            for (var di = 0; di < dc; ++di) {
                var d = data[di];
                if (d) {
                    var eid = d[0];
                    if (eid !== undefined && eid !== null) {
                        ces[eid] = tilib_UpdateCache(ces[eid], d);
                    }
                }
            }
        }
    };
    this.removeElement = function (n, keys) {
        if (keys) {
            var ces = _elements[n];
            if (ces) {
                var kc = keys.length;
                for (var ki = 0; ki < kc; ++ki) {
                    var key = keys[ki];
                    if (key) {
                        delete ces[key];
                    }
                }
            }
        }
    };
    this.setElementPrimitive = function (n, data) {
        if (data) {
            var ces = {};
            _elements[n] = ces;
            var dc = data.length;
            for (var di = 0; di < dc; ++di) {
                var d = data[di];
                if (d) {
                    var eid = d;
                    if (eid) {
                        ces[eid] = d;
                    }
                }
            }
            ces.count = dc;
        }
    };
    var _translations = {};
    this.setTranslation = function (n, t) {
        _translations[n] = t;
    };
    this.getTranslation = function (n) {
        return _translations[n];
    };
    var _templates = {};
    this.setTemplate = function (n, t) {
        _templates[n] = t;
    };
    this.getTemplate = function (n) {
        return _templates[n];
    };
    var _tokens = {};
    this.setToken = function (n, t) {
        _tokens[n] = t;
    };
    this.getToken = function (n) {
        return _tokens[n];
    };
    var _windows = {};
    this.getWindow = function (n) {
        var w = _windows[n];
        if (w) {
            if (!w.closed) {
                return w;
            }
            delete _windows[n];
        }
        return null;
    };
    this.setWindow = function (w) {
        if (w && w.name) {
            _windows[w.name] = w;
        }
    };
    var _models = {};
    this.setModel = function (n, m) {
        _models[n] = m;
    };
    this.getModel = function (n) {
        return _models[n];
    };
    this.triggerTimer = function () {
        for (i in _models) {
            var m = _models[i];
            if (m) {
                if (m.onTime) {
                    m.onTime();
                }
            }
        }
        setTimeout("$P.triggerTimer()", 1000);
    };
    var _requests = {};
    this.sendRequest = function (n, url) {
        var r = _requests[n];
        if (!r) {
            r = {
                sending: false,
                request: new XMLHttpRequest()
            };
            r.request.onreadystatechange = function () {
                if (r.request.readyState == 4) {
                    r.sending = false;
                    var c = r.request.responseText;
                    if (c) {
                        try {
                            eval(c);
                        } catch (e) {}
                    }
                }
            }
            _requests[n] = r;
        }
        if (!r.sending) {
            r.sending = true;
            r.request.open("GET", url, true);
            r.request.onreadystatechange = r.request.onreadystatechange;
            r.request.send(null);
            return true;
        }
        return false;
    };
    this.postRequest = function (url, param) {
        var _request = new XMLHttpRequest();
        _request.open("POST", url, false);
        _request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        _sendingRequest = true;
        _request.send(param);
        var c = _request.responseText;
        if (c) {
            try {
                eval(c);
            } catch (e) {}
        }
    }
    var _states = {};
    this.getState = function (n) {
        var state = _states[n];
        if (!state) {
            _states[n] = state = {};
        }
        return state;
    };
    this.onReload = function () {
        window.location.reload();
    };
    this.onIdle = function (m, d) {
        var model = _models[m];
        if (model && model.onIdle) {
            if (d != undefined) {
                model.onIdle(d);
            } else {
                model.onIdle();
            }
        }
    };
    this.onUpdate = function (m, d) {
        var model = _models[m];
        if (model && model.onUpdate) {
            if (d != undefined) {
                model.onUpdate(d);
            } else {
                model.onUpdate();
            }
        }
    };
    this.onExecution = function (id) {
        var f = document.getElementById(id);
        if (f) {
            var w = f.contentWindow;
            if (w) {
                if (w.document.body) {
                    var c;
                    if (typeof (w.document.body.innerText) != 'undefined') {
                        c = w.document.body.innerText;
                    } else if (typeof (w.document.body.textContent) != 'undefined') {
                        c = w.document.body.textContent;
                    } else if (typeof (w.document.body.innerHTML) != 'undefined') {
                        c = w.document.body.innerHTML;
                    }
                    if (c) {
                        try {
                            eval(c);
                        } catch (e) {}
                    }
                }
            }
        }
    };
    this.goUrl = function (base, extent) {
        if (history.pushState) {
            if (extent) {
                window.top.location.href = base + extent;
            } else {
                window.top.location.href = base;
            }
        } else {
            if (extent) {
                window.top.location.href = base + '#!/' + extent;
            } else {
                window.top.location.href = base;
            }
        }
    };
}
var $P = new __PageCache();

function $E(e) {
    return $P.getElement(e);
}

function $T(t) {
    return $P.getToken(t);
}

function $M(m) {
    return $P.getModel(m);
}

function $S(m) {
    return $P.getState(m);
}

function startGlobalTimer() {
    $P.triggerTimer();
}

function od_CacheEvent(id) {
    var _id = id;
    this.getId = function () {
        return _id;
    }
    this.getType = function () {
        return 'event';
    }
    var _tags = {};
    var _itags = [];
    var _pais = null;
    var _sports = [];
    this.update = function (tags, ods, eds, ps) {
        _pais = null;
        _updateTags(tags, ps);
        _deleteOdds(ods);
        _deleteEvents(eds);
        _normalize();
    };

    function _updateTags(tags, ps) {
        if (!tags) return;
        var ss = $E('sports');
        var ts = $E('tournaments');
        var cts = _tags;
        var now = new Date();
        var tc = tags.length;
        for (var ti = 0; ti < tc; ++ti) {
            var nt = tags[ti];
            if (!nt) continue;
            var ne = nt[2];
            if (!ne) continue;
            var eid = ne[0];
            if (!eid) continue;
            var ct = cts[eid];
            if (!ct) {
                var sid = nt[0];
                var tid = nt[1];
                if (sid && tid) {
                    ct = [];
                    cts[eid] = ct;
                    ct[0] = ss[sid];
                    ct[1] = ts[tid];
                    ct[4] = [0, {}, {}];
                }
            }
            if (ct) {
                var nx = nt[3];
                ct[2] = tilib_UpdateCache(ct[2], ne);
                ct[3] = tilib_UpdateCache(ct[3], nx);
                _updateOdds(ct[4], nt[4], ps);
                if (nt[5] !== undefined) ct[5] = nt[5];
                if (!ct[6] || (nx && (nx[1] || nx[2]))) {
                    ct[6] = now;
                }
                ct[7] = tilib_UpdateCache(ct[7], nt[6]);
            }
        }
    }

    function _updateOdds(coset, nos, ps) {
        if (!nos) return;
        coset[0] = nos[0];
        var oc = nos.length;
        if (oc <= 1) return;
        var codo = coset[1];
        for (var oi = 1; oi < oc; ++oi) {
            var no = nos[oi];
            if (!no) continue;
            var oid = no[0];
            var nob = no[1];
            var co = codo[oid];
            if (!co) {
                co = [oid];
                codo[oid] = co;
            }
            co[1] = tilib_UpdateCache(co[1], nob);
            nps = no[2];
            if (nps) {
                var cps = co[2];
                nps = tilib_UpdateCache(cps, nps);;
                if (cps) {
                    var pc = cps.length;
                    for (var pi = 0; pi < pc; ++pi) {
                        var cp = cps[pi];
                        var np = nps[pi];
                        if (!(cp && np && np != cp)) continue;
                        if (!_pais) _pais = {};
                        var pai = 0;
                        if (ps == 3) {
                            pai = (np > cp) ? 1 : -1;
                        } else {
                            if (cp > 0) {
                                if (np > 0) {
                                    pai = (np > cp) ? 1 : -1;
                                } else {
                                    pai = 1;
                                }
                            } else {
                                if (np > 0) {
                                    pai = -1;
                                } else {
                                    pai = (np > cp) ? 1 : -1;
                                }
                            }
                        }
                        _pais[oid + '-' + pi] = pai;
                    }
                }
                co[2] = nps;
            }
        }
    }

    function _deleteOdds(ods) {
        if (!ods) return;
        var cts = _tags;
        var odc = ods.length;
        for (var odi = 0; odi < odc; ++odi) {
            var od = ods[odi];
            if (!od) continue;
            var oc = od.length;
            if (oc <= 1) continue;
            var eid = od[0];
            if (!eid) continue;
            var ct = cts[eid];
            if (!ct) continue;
            var coset = ct[4];
            if (!coset) continue;
            var codo = coset[1];
            if (!codo) continue;
            for (var oi = 1; oi < oc; ++oi) {
                var oid = od[oi];
                if (codo[oid]) {
                    delete codo[oid];
                }
            }
        }
    }

    function _deleteEvents(eids) {
        if (!eids) return;
        var cts = _tags;
        var eidc = eids.length;
        for (var eidi = 0; eidi < eidc; ++eidi) {
            var eid = eids[eidi];
            if (!eid) continue;
            if (cts[eid]) {
                delete cts[eid];
            }
        }
    }

    function _normalize() {
        var cts = _tags;
        if (!cts) return;
        var itags = [];
        var sports = [];
        for (var eid in cts) {
            var ct = cts[eid];
            if (!ct) continue;
            var coset = ct[4];
            if (!coset) continue;
            sports[ct[0][0]] = true;
            var codo = coset[1];
            var codm = {};
            for (var oid in codo) {
                var co = codo[oid];
                if (!co) continue;
                var cob = co[1];
                var mdid = cob[2];
                var com = codm[mdid];
                if (!com) {
                    com = [];
                    codm[mdid] = com;
                }
                com.push(co);
            }
            if (codm) {
                for (mdid in codm) {
                    com = codm[mdid];
                    if (com) {
                        com.sort(_sortOddsCallback);
                    }
                }
            }
            coset[2] = codm;
            itags.push(ct);
        }
        itags.sort(_sortTagCallback);
        _itags = itags;
        _sports = sports;
    }

    function _sortTagCallback(tag1, tag2) {
        var event1 = tag1[2];
        var event2 = tag2[2];
        var showtime1 = event1[5];
        var showtime2 = event2[5];
        var matchcode1 = event1[3];
        var matchcode2 = event2[3];
        if ($T('site').getValue('sort') == 2) {
            if (showtime1 != showtime2) {
                return (showtime1 < showtime2) ? -1 : 1;
            }
            if (matchcode1 != matchcode2) {
                return (matchcode1 < matchcode2) ? -1 : 1;
            }
            return tag1[0] - tag2[0];
        } else {
            if (matchcode1 != matchcode2) {
                return (matchcode1 < matchcode2) ? -1 : 1;
            }
            if (showtime1 != showtime2) {
                return (showtime1 < showtime2) ? -1 : 1;
            }
            return tag1[0] - tag2[0];
        }
    }

    function _sortOddsCallback(odds1, odds2) {
        var mgid1 = odds1[1][1];
        var mgid2 = odds2[1][1];
        var maxbet1 = odds1[1][4];
        var maxbet2 = odds2[1][4];
        var resultId1 = odds1[1][6];
        var resultId2 = odds2[1][6];
        if (mgid1 != mgid2) {
            if (mgid1 == 0) {
                return -1;
            }
            if (mgid2 == 0) {
                return 1;
            }
            var mg1 = $E('market-groups')[mgid1];
            var mg2 = $E('market-groups')[mgid2];
            if (mg1 && mg2) {
                if (mg1[7] != mg2[7]) {
                    return (mg1[7] < mg2[7]) ? -1 : 1;
                }
            }
        }
        if (resultId1 != resultId2) {
            return (resultId1 < resultId2) ? -1 : 1;
        }
        if (maxbet1 != maxbet2) {
            return (maxbet1 > maxbet2) ? -1 : 1;
        }
        return (odds1[0] < odds2[0]) ? -1 : 1;
    }
    this.normalize = function () {
        _normalize();
    };
    this.getTags = function () {
        return _itags;
    };
    this.getPAIs = function () {
        return _pais;
    };
    this.clearPAIs = function () {
        if (_pais) {
            _pais = null;
            return true;
        } else {
            return false;
        }
    };
    this.getTag = function (eid, oid) {
        var tag = _tags[eid];
        if (tag && oid != undefined) {
            var coset = tag[4];
            if (coset) {
                var codo = coset[1];
                if (!codo[oid]) {
                    tag = undefined;
                }
            } else {
                tag = undefined;
            }
        }
        return tag;
    };
    this.getSports = function () {
        return _sports;
    };
}

function od_CacheOutright(id) {
    var _id = id;
    this.getId = function () {
        return _id;
    }
    this.getType = function () {
        return 'outright';
    }
    var _tags = {};
    var _itags = [];
    var _pais = null;
    var _sports = [];
    this.update = function (os, ods) {
        _pais = null;
        _updateOutrights(os);
        _deleteOutrights(ods);
        _normalize();
    };
    this.updateTournament = function () {
        var cts = _tags;
        if (cts) {
            var ts = $E('tournaments');
            var itags = [];
            var sports = [];
            var tid;
            for (var oid in cts) {
                var ct = cts[oid];
                if (ct) {
                    tid = ct[2][4];
                    ct[1] = ts[tid];
                    itags.push(ct);
                }
            }
            itags.sort(_sortTagCallback);
            _itags = itags;
            _sports = sports;
        }
    };

    function _updateOutrights(os) {
        var ss = $E('sports');
        var ts = $E('tournaments');
        var cts = _tags;
        if (os) {
            var oc = os.length;
            for (var oi = 0; oi < oc; ++oi) {
                var no = os[oi];
                if (no) {
                    var oid = no[0];
                    var ct = cts[oid];
                    if (!ct) {
                        var sid = no[3];
                        var tid = no[4];
                        if (sid && tid) {
                            ct = [];
                            cts[oid] = ct;
                            ct[0] = ss[sid];
                            ct[1] = ts[tid];
                            ct[2] = no;
                        }
                    } else {
                        var cp = ct[2][2];
                        var np = no[2];
                        if (cp && np && np != cp) {
                            if (!_pais) _pais = {};
                            _pais[oid] = (np > cp) ? 1 : -1;
                        }
                        ct[2] = tilib_UpdateCache(ct[2], no);
                    }
                }
            }
        }
    }

    function _deleteOutrights(ods) {
        if (ods) {
            var cts = _tags;
            var odc = ods.length;
            for (var odi = 0; odi < odc; ++odi) {
                var oid = ods[odi];
                if (oid) {
                    if (cts[oid]) {
                        delete cts[oid];
                    }
                }
            }
        }
    }

    function _normalize() {
        var cts = _tags;
        if (cts) {
            var itags = [];
            var sports = [];
            for (var oid in cts) {
                var ct = cts[oid];
                if (ct) {
                    itags.push(ct);
                }
            }
            itags.sort(_sortTagCallback);
            _itags = itags;
            _sports = sports;
        }
    }

    function _sortTagCallback(t1, t2) {
        var te1 = t1[1];
        var te2 = t2[1];
        var o1 = t1[2];
        var o2 = t2[2];
        var o1_price = o1[2];
        var o2_price = o2[2];
        var t1_tcode = (te1[9] == undefined) ? '' : te1[9];
        var t2_tcode = (te2[9] == undefined) ? '' : te2[9];
        var t1_tname = te1[1];
        var t2_tname = te2[1];
        var o1_ecode = o1[8];
        var o2_ecode = o2[8];
        var o1_isLive = o1[1];
        var o2_isLive = o1[1];
        if (o1_isLive == o2_isLive) {
            if (t1_tcode == t2_tcode) {
                if (t1_tname == t2_tname) {
                    if (o1_price == o2_price) {
                        return (o1_ecode < o2_ecode) ? -1 : 1;
                    } else {
                        return (o1_price < o2_price) ? -1 : 1;
                    }
                } else {
                    return (t1_tname < t2_tname) ? -1 : 1;
                }
            } else {
                if (t1_tcode == '' && t2_tcode != '') {
                    return 1;
                } else if (t1_tcode != '' && t2_tcode == '') {
                    return -1;
                } else {
                    return (t1_tcode < t2_tcode) ? -1 : 1;
                }
            }
        } else {
            return (o1_isLive > o2_isLive) ? -1 : 1;
        }
    }
    this.getTags = function () {
        return _itags;
    };
    this.getPAIs = function () {
        return _pais;
    };
    this.clearPAIs = function () {
        if (_pais) {
            _pais = null;
            return true;
        } else {
            return false;
        }
    };
    this.getTag = function (oid) {
        return _tags[oid];
    };
    this.getSports = function () {
        return _sports;
    };
}

function __EuroCacheStreaming() {
    var _video = null;
    this.update = function (video) {
        var updated = false;
        var cv = _video;
        var nv = video;
        if (!cv || cv[0] != nv[0]) {
            cv = nv;
            updated = true;
        } else {
            if (cv[1] != nv[1]) {
                updated = true;
            }
            cv = tilib_UpdateCache(cv, nv);
        }
        _video = cv;
        return updated;
    }
    this.clear = function () {
        _video = null;
    };
    this.getVideo = function () {
        return _video;
    };
}

function __EuroModel() {
    var _hash = null;
    this.detectHash = function () {
        var h = window.location.hash;
        if (h && h.length > 3 && h.charAt(0) == '#' && h.charAt(1) == '!' && h.charAt(2) == '/') {
            _hash = h.substring(3);
            _hash = encodeURIComponent(decodeURIComponent(_hash));
        }
    }
    this.getHash = function () {
        var hash = _hash;
        _hash = null;
        return hash;
    }
    this.onToken = function (pid, sid, rid, tid, eid, dt, mt) {
        var token = $T('od');
        if (pid) {
            if (pid != token.getValue('pid')) {
                token.setValue('pid', pid);
                $M('od').onPageChanged();
            }
            if (sid || sid === 0) {
                token.setValue('sid', sid);
                if (rid || rid === 0) {
                    token.setValue('rid', rid);
                }
                if (tid || tid === 0) {
                    token.setValue('tid', tid);
                    if (eid || eid === 0) {
                        token.setValue('eid', eid);
                    }
                }
            }
            if (dt || dt === 0) {
                token.setValue('dt', dt);
            }
            if (mt || mt === 0) {
                token.setValue('mt', mt);
            }
        }
    };
    this.refineUrl = function () {
        var t = $T('od');
        switch (t.getValue('pid')) {
        case 35:
        case 25:
        case 15:
            $M('od').moveTo(t.getValue('eid'));
            break;
        case 2:
        case 11:
        case 12:
        case 13:
        case 14:
        case 21:
        case 22:
        case 23:
        case 24:
        case 31:
            this.moveTo(t.getValue('pid'), t.getValue('sid'), t.getValue('rid'), t.getValue('tid'), 0, 0, t.getValue('dt'), t.getValue('mt'));
            break;
        }
    };
    this.onLanguage = function (event, code) {
        if (!event) event = window.event;
        if (!_onLanguage(event, code)) {
            event.returnValue = false;
            return false;
        }
        return true;
    };

    function _onLanguage(event, code) {
        var token = $T('site');
        if (token && !token.getValue('seo')) {
            var sb = [];
            sb.push('/');
            sb.push(code);
            sb.push('/data/language?tk=');
            sb.push($T('od').getToken());
            $P.sendRequest('la', sb.join(''));
            return false;
        }
        return true;
    };
    this.goLanding = function () {
        var sb = [];
        sb.push('/');
        var lang = $T('site').getValue('lang');
        if (lang != 'en') {
            sb.push(lang);
            sb.push('/');
        }
        sb.push('betting.aspx');
        window.top.location.href = sb.join('');
        return true;
    };
    this.goHome = function () {
        var token = $M('euro').moveTo(2);
        if (token) {
            return $M('od').onReload(token);
        }
        return false;
    }
    this.goSport = function (sid, dt, mt) {
        var token = $M('euro').moveTo(11, sid, 0, 0, 0, 0, dt, mt);
        if (token) {
            if ($M('od').onReload(token)) {
                var m = $M('rp');
                if (m && m.onSportChange) {
                    $M('rp').onSportChange(sid);
                }
            }
            return true;
        }
        return false;
    };
    this.goRegion = function (sid, rid, dt, mt) {
        var token = $M('euro').moveTo(12, sid, rid, 0, 0, 0, dt, mt);
        if (token) {
            return $M('od').onReload(token);
        }
        return false;
    };
    this.goTournament = function (tid, dt, mt) {
        var t = $E('tournaments')[tid];
        if (t) {
            var token = $M('euro').moveTo(13, t[2], t[3], tid, 0, 0, dt, mt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goOutright = function (sid, rid, dt, tid) {
        var r = $E('regions')[rid];
        if (r) {
            var token = $M('euro').moveTo(14, sid, rid, tid, 0, 0, dt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goLiveBetting = function (sid) {
        if (!sid) sid = $T('od').getValue('sid');
        var token = $M('euro').moveTo(21, sid);
        if (token) {
            return $M('od').onReload(token);
        }
        return false;
    }
    this.goLiveSport = function (sid, dt) {
        var token = $M('euro').moveTo(21, sid, 0, 0, 0, 0, 1);
        if (token) {
            if ($M('od').onReload(token)) {
                var m = $M('rp');
                if (m && m.onSportChange) {
                    $M('rp').onSportChange(sid);
                }
                return true;
            }
        }
        return false;
    };
    this.goLiveRegion = function (sid, rid, dt, mt) {
        var token = $M('euro').moveTo(22, sid, rid, 0, 0, 0, 1, mt);
        if (token) {
            return $M('od').onReload(token);
        }
        return false;
    };
    this.goLiveTournament = function (tid, dt, mt) {
        var t = $E('tournaments')[tid];
        if (t) {
            var token = $M('euro').moveTo(23, t[2], t[3], tid, 0, 0, 1, mt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goLiveOutright = function (sid, rid, dt) {
        var r = $E('regions')[rid];
        if (r) {
            var token = $M('euro').moveTo(24, sid, rid, 0, 0, 0, 1);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goMixParlay = function (sid, dt, mt) {
        if (!sid) sid = $T('od').getValue('sid');
        var token = $M('euro').moveTo((sid) ? 31 : 30, sid, 0, 0, 0, 0, dt, mt);
        if (token) {
            return $M('od').onReload(token);
        }
        return false;
    }
    this.goEufaEuroEvent = function (sid, dt) {
        var token = $M('euro').moveTo(60, 1, $T('site').getValue('eufaeuro-rid'), 0, 0, 0, dt ? dt : 0);
        if (token) {
            if ($M('od').onReload(token)) {
                var m = $M('rp');
            }
            return true;
        }
        return false;
    };
    this.goEufaEuroEventTournament = function (tid, dt, mt) {
        var t = $E('tournaments')[tid];
        if (t) {
            var token = $M('euro').moveTo(63, t[2], t[3], tid, 0, 0, dt, mt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goEufaEuroOutright = function (sid, rid, dt) {
        var r = $E('regions')[rid];
        if (r) {
            var token = $M('euro').moveTo(64, sid, $T('site').getValue('eufaeuro-rid'), 0, 0, 0, dt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goLiveEufaEuroEvent = function () {
        var token = $M('euro').moveTo(70, 1, $T('site').getValue('eufaeuro-rid'));
        if (token) {
            return $M('od').onReload(token);
        }
        return false;
    };
    this.goLiveEufaEuroEventTournament = function (tid, dt, mt) {
        var t = $E('tournaments')[tid];
        if (t) {
            var token = $M('euro').moveTo(73, t[2], t[3], tid, 0, 0, 1, mt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goLiveEufaEuroOutright = function (sid, rid, dt) {
        var r = $E('regions')[rid];
        if (r) {
            var token = $M('euro').moveTo(74, sid, rid, 0, 0, 0, 1);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goBigEvent = function (sid, dt) {
        var token = $M('euro').moveTo(40, sid ? sid : 0, $T('site').getValue('bigevent-rid'), 0, 0, 0, dt ? dt : 0);
        if (token) {
            if ($M('od').onReload(token)) {
                var m = $M('rp');
            }
            return true;
        }
        return false;
    };
    this.goBigEventSport = function (sid, dt, mt) {
        var token = $M('euro').moveTo(41, sid, $T('site').getValue('bigevent-rid'), 0, 0, 0, dt, mt);
        if (token) {
            if ($M('od').onReload(token)) {
                var m = $M('rp');
                if (m && m.onSportChange) {
                    $M('rp').onSportChange(sid);
                }
            }
            return true;
        }
        return false;
    };
    this.goBigEventTournament = function (tid, dt, mt) {
        var t = $E('tournaments')[tid];
        if (t) {
            var token = $M('euro').moveTo(43, t[2], t[3], tid, 0, 0, dt, mt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goBigEventOutright = function (sid, rid, dt) {
        var r = $E('regions')[rid];
        if (r) {
            var token = $M('euro').moveTo(44, sid, $T('site').getValue('bigevent-rid'), 0, 0, 0, dt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goLiveBigEvent = function () {
        var token = $M('euro').moveTo(50, 0, $T('site').getValue('bigevent-rid'));
        if (token) {
            return $M('od').onReload(token);
        }
        return false;
    }
    this.goLiveBigEventSport = function (sid, dt, mt) {
        var token = $M('euro').moveTo(51, sid, $T('site').getValue('bigevent-rid'), 0, 0, 0, 1, mt);
        if (token) {
            if ($M('od').onReload(token)) {
                var m = $M('rp');
                if (m && m.onSportChange) {
                    $M('rp').onSportChange(sid);
                }
                return true;
            }
        }
        return false;
    };
    this.goLiveBigEventTournament = function (tid, dt, mt) {
        var t = $E('tournaments')[tid];
        if (t) {
            var token = $M('euro').moveTo(53, t[2], t[3], tid, 0, 0, 1, mt);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.goLiveBigEventOutright = function (sid, rid, dt) {
        var r = $E('regions')[rid];
        if (r) {
            var token = $M('euro').moveTo(54, sid, rid, 0, 0, 0, 1);
            if (token) {
                return $M('od').onReload(token);
            }
        }
        return false;
    };
    this.getEuroUrlBase = function () {
        var sb = [];
        sb.push('/');
        var lang = $T('site').getValue('lang');
        if (lang != 'en') {
            sb.push(lang);
            sb.push('/');
        }
        sb.push($T('site').getValue('euro'));
        sb.push('/');
        return sb.join('');
    }

    function _getTwoDigits(n) {
        if (n < 10) {
            return '0' + n;
        } else {
            return n;
        }
    }
    this.moveTo = function (pid, sid, rid, tid, eid, ename, sdt, smt, dontChangeURL) {
        var base = this.getEuroUrlBase();
        var pathname = decodeURIComponent(window.top.location.pathname);
        if (pid == 2) {
            if (base != pathname) {
                if ($T('site').getValue('seo')) {
                    window.top.location.href = base;
                    return null;
                } else {
                    if (history.pushState) {
                        history.pushState(null, null, base);
                        window.location.reload();
                    } else if (base == pathname) {
                        window.top.location.hash = '!';
                    } else {
                        window.top.location.href = base + '#!/';
                    }
                }
            }
            return;
        }
        var poutright = $E('pages')[14];
        var plivebetting = $E('pages')[20];
        var pmixparlay = $E('pages')[30];
        var rbigevent = $E('regions')[$T('site').getValue('bigevent-rid')];
        var rEufaEuroEvent = $E('regions')[$T('site').getValue('eufaeuro-rid')];
        var s = (sid) ? $E('sports')[sid] : undefined;
        var r = (rid) ? $E('regions')[rid] : undefined;
        var t = (tid) ? $E('tournaments')[tid] : undefined;
        if (!sdt) sdt = $T('od').getValue('dt');
        if (!smt) smt = $T('od').getValue('mt');
        var dt = $E('date-tabs')[sdt];
        var mt = $E('market-tabs')[smt];
        var now = $T('od').getValue('cd');
        var today = new Date(parseInt(now.substring(0, 4), 10), parseInt(now.substring(4, 6), 10) - 1, parseInt(now.substring(6, 8), 10));
        var time = 24 * 60 * 60 * 1000;
        var date = new Date(today.getTime() + (sdt - 1) * time);
        sb = [];
        while (sb.length <= 0) {
            switch (pid) {
            case 2:
                sb.push('');
                break;
            case 20:
            case 30:
                if (s) {
                    pid++;
                    break;
                } else {
                    if (pid == 21) {
                        sb.push($Code(plivebetting[1]));
                    } else if (pid == 31) {
                        sb.push($Code(pmixparlay[1]));
                    }
                    rid = undefined;
                    tid = undefined;
                    eid = undefined;
                    sb.push('');
                }
                break;
            case 40:
                sb.push($Code(rbigevent[1]));
                sb.push('/');
                if (sdt > 1 && sdt < 9) {
                    if (sdt == 8) {
                        sb.push($Code(dt[1]));
                    } else {
                        sb.push(date.getFullYear());
                        sb.push('-');
                        sb.push(_getTwoDigits(date.getMonth() + 1));
                        sb.push('-');
                        sb.push(_getTwoDigits(date.getDate()));
                    }
                }
                sid = undefined;
                tid = undefined;
                eid = undefined;
                sb.push('');
                break;
            case 50:
                if (s) {
                    pid++;
                    break;
                } else {
                    sb.push($Code(plivebetting[1]));
                    sb.push('/')
                    sb.push($Code(rbigevent[1]));
                    tid = undefined;
                    eid = undefined;
                }
                break;
            case 60:
                sb.push($Code(rEufaEuroEvent[1]));
                sb.push('/');
                if (sdt > 1 && sdt < 9) {
                    if (sdt == 8) {
                        sb.push($Code(dt[1]));
                    } else {
                        sb.push(date.getFullYear());
                        sb.push('-');
                        sb.push(_getTwoDigits(date.getMonth() + 1));
                        sb.push('-');
                        sb.push(_getTwoDigits(date.getDate()));
                    }
                }
                tid = undefined;
                eid = undefined;
                sb.push('');
                break;
            case 70:
                sb.push($Code(plivebetting[1]));
                sb.push('/')
                sb.push($Code(rEufaEuroEvent[1]));
                tid = undefined;
                eid = undefined;
                break;
            case 11:
            case 21:
            case 31:
            case 41:
            case 51:
                if (s) {
                    if (pid == 21) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                    } else if (pid == 31) {
                        sb.push($Code(pmixparlay[1]));
                        sb.push('/');
                    } else if (pid == 41) {
                        sb.push($Code(rbigevent[1]));
                        sb.push('/');
                    } else if (pid == 51) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                        sb.push($Code(rbigevent[1]));
                        sb.push('/');
                    }
                    if (pid == 31 && s[5]) {
                        sb.push($Code(s[5]));
                    } else {
                        sb.push($Code(s[1]));
                    }
                    if (pid == 11 || pid == 31 || pid == 41) {
                        sb.push('/');
                        if (sdt > 1 && sdt < 9) {
                            if (sdt == 8) {
                                sb.push($Code(dt[1]));
                            } else {
                                sb.push(date.getFullYear());
                                sb.push('-');
                                sb.push(_getTwoDigits(date.getMonth() + 1));
                                sb.push('-');
                                sb.push(_getTwoDigits(date.getDate()));
                            }
                        }
                    }
                    if (pid < 40) {
                        rid = undefined;
                    }
                    tid = undefined;
                    eid = undefined;
                    break;
                }
                pid = 2;
                break;
            case 12:
            case 22:
                if (s && r) {
                    if (pid == 22) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                    }
                    sb.push($Code(s[1]));
                    sb.push('/');
                    sb.push($Code(r[1]));
                    if (pid == 12) {
                        sb.push('/');
                        if (sdt > 1 && sdt < 9) {
                            if (sdt == 8) {
                                sb.push($Code(dt[1]));
                            } else {
                                sb.push(date.getFullYear());
                                sb.push('-');
                                sb.push(_getTwoDigits(date.getMonth() + 1));
                                sb.push('-');
                                sb.push(_getTwoDigits(date.getDate()));
                            }
                        }
                    }
                    tid = undefined;
                    eid = undefined;
                    break;
                }
                pid--;
                break;
            case 13:
            case 23:
            case 43:
            case 53:
            case 63:
            case 73:
                if (s && t) {
                    if (pid == 23) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                    } else if (pid == 43) {
                        sb.push($Code(rbigevent[1]));
                        sb.push('/');
                    } else if (pid == 53) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                        sb.push($Code(rbigevent[1]));
                        sb.push('/');
                    } else if (pid == 63) {
                        sb.push($Code(rEufaEuroEvent[1]));
                        sb.push('/');
                    } else if (pid == 73) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                        sb.push($Code(rEufaEuroEvent[1]));
                        sb.push('/');
                    }
                    if (pid != 63 && pid != 73) {
                        sb.push($Code(s[1]));
                        sb.push('/');
                    }
                    sb.push($Code(t[1]));
                    if (pid == 13 || pid == 43 || pid == 63) {
                        sb.push('/');
                        if (sdt > 1 && sdt < 9) {
                            if (sdt == 8) {
                                sb.push($Code(dt[1]));
                            } else {
                                sb.push(date.getFullYear());
                                sb.push('-');
                                sb.push(_getTwoDigits(date.getMonth() + 1));
                                sb.push('-');
                                sb.push(_getTwoDigits(date.getDate()));
                            }
                        }
                    }
                    eid = undefined;
                    break;
                }
                if (pid == 63) {
                    pid = 60;
                } else if (pid == 73) {
                    pid = 70;
                } else {
                    pid--;
                    break;
                }
            case 14:
            case 24:
            case 44:
            case 54:
            case 64:
            case 74:
                if (s && r) {
                    if (pid == 24) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                    } else if (pid == 44) {
                        sb.push($Code(rbigevent[1]));
                        sb.push('/');
                    } else if (pid == 54) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                        sb.push($Code(rbigevent[1]));
                        sb.push('/');
                    } else if (pid == 64) {
                        sb.push($Code(rEufaEuroEvent[1]));
                        sb.push('/');
                    } else if (pid == 74) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                        sb.push($Code(rEufaEuroEvent[1]));
                        sb.push('/');
                    }
                    if (pid != 64 && pid != 74) {
                        sb.push($Code(s[1]));
                        sb.push('/');
                    }
                    if (pid < 40) {
                        sb.push($Code(r[1]));
                        sb.push('/');
                    }
                    sb.push($Code(poutright[1]));
                    if (pid == 14 || pid == 44) {
                        sb.push('/');
                        if (sdt > 1 && sdt < 9) {
                            if (sdt == 8) {
                                sb.push($Code(dt[1]));
                            } else {
                                sb.push(date.getFullYear());
                                sb.push('-');
                                sb.push(_getTwoDigits(date.getMonth() + 1));
                                sb.push('-');
                                sb.push(_getTwoDigits(date.getDate()));
                            }
                        }
                        if (tid) {
                            sb.push('/');
                            sb.push(tid);
                            sb.push('/');
                            sb.push($Code(t[1]));
                        }
                    }
                    eid = undefined;
                    break;
                }
                pid--;
                break;
            case 15:
            case 25:
            case 35:
            case 45:
            case 55:
            case 65:
            case 75:
                if (s && t && eid && ename) {
                    if (pid == 25) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                    } else if (pid == 35) {
                        sb.push($Code(pmixparlay[1]));
                        sb.push('/');
                    } else if (pid == 45) {
                        sb.push($Code(rbigevent[1]));
                        sb.push('/');
                    } else if (pid == 55) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                        sb.push($Code(rbigevent[1]));
                        sb.push('/');
                    } else if (pid == 65) {
                        sb.push($Code(rEufaEuroEvent[1]));
                        sb.push('/');
                    } else if (pid == 75) {
                        sb.push($Code(plivebetting[1]));
                        sb.push('/');
                        sb.push($Code(rEufaEuroEvent[1]));
                        sb.push('/');
                    }
                    if (pid == 15 || pid == 25 || pid == 45 || pid == 55) {
                        sb.push($Code(s[1]));
                        sb.push('/');
                        sb.push($Code(t[1]));
                        sb.push('/');
                    } else if (pid == 35) {
                        if (s[5]) {
                            sb.push($Code(s[5]));
                        } else {
                            sb.push($Code(s[1]));
                        }
                        sb.push('/');
                    }
                    sb.push(eid);
                    sb.push('/');
                    sb.push(ename);
                    break;
                }
                pid = 13;
                break;
            default:
                pid = 2;
                break;
            }
        }
        var extent = sb.join('');
        var tk = $T('od').clone();
        tk.setValue('pid', (pid) ? pid : 0);
        tk.setValue('sid', (sid) ? sid : 0);
        tk.setValue('rid', (rid) ? rid : 0);
        tk.setValue('tid', (tid) ? tid : 0);
        tk.setValue('eid', (eid) ? eid : 0);
        tk.setValue('dt', sdt);
        tk.setValue('mt', smt);
        if (base + extent != pathname) {
            if ($T('site').getValue('seo')) {
                if (dontChangeURL) {
                    window.top.location.href = base + extent;
                    return null;
                }
            } else {
                if (history.pushState) {
                    history.pushState(null, null, base + extent);
                } else if (base == pathname) {
                    if (window.top.location.hash != '#!/' + extent) {
                        window.top.location.hash = '!/' + extent;
                    }
                } else {
                    window.top.location.href = base + '#!/' + extent;
                }
            }
        }
        return tk;
    }
    this.onLogout = function () {
        var sb = [];
        sb.push('/');
        sb.push($T('site').getValue('lang'));
        sb.push('/');
        sb.push('data/logout');
        $P.sendRequest('lo', sb.join(''));
    }
    this.onShowHideBetCredit = function (isShowing) {
        var creditDiv = document.getElementById('bet-credit-container');
        var iconShow = document.getElementById('icon-show-credit');
        var iconHide = document.getElementById('icon-hide-credit');
        if (creditDiv) {
            if (isShowing) {
                iconShow.className = tilib_AddClassItem(iconShow.className, 'hide');
                iconHide.className = tilib_RemoveClassItem(iconHide.className, 'hide');
                creditDiv.className = tilib_RemoveClassItem(creditDiv.className, 'hide');
            } else {
                iconHide.className = tilib_AddClassItem(iconHide.className, 'hide');
                iconShow.className = tilib_RemoveClassItem(iconShow.className, 'hide');
                creditDiv.className = tilib_AddClassItem(creditDiv.className, 'hide');
            }
        }
    }
    this.AddClassName = function (control, item) {
        var name = control.className;
        control.className = tilib_AddClassItem(name, item);
    }
    this.RemoveClassName = function (control, item) {
        var name = control.className;
        control.className = tilib_RemoveClassItem(name, item);
    }
    this.onLanguageClick = function () {
        _showHideLanguageSelection();
    }
}
$P.setModel('euro', new __EuroModel());

function $Code(t) {
    return tilib_ConvertNameToCode(t);
}

function $Name(t) {
    return tilib_ConvertNameToHTML(t);
}
var _LanguageShowingState = false;

function _showHideLanguageSelection() {
    var div = document.getElementById('lang-menu');
    if (!div) {
        return false;
    }
    if (_LanguageShowingState) {
        div.className = tilib_AddClassItem(div.className, 'Hide');
        window.removeEventListener('mousedown', _onMouseDown);
    } else {
        div.className = tilib_RemoveClassItem(div.className, 'Hide');
        window.addEventListener("mousedown", _onMouseDown, false);
    }
    _LanguageShowingState = !_LanguageShowingState;
};

function hideLanguage() {
    _showHideLanguageSelection();
}

function _onMouseDown(event) {
    var e = event;
    var target = (e.target || e.srcElement);
    var node = target.parentNode;
    var isWithinArea = false;
    while (node) {
        if (node.id == 'lang-menu' || node.id == 'selected-lang') {
            isWithinArea = true;
            return true;
        }
        node = node.parentNode;
    }
    if (!isWithinArea) {
        hideLanguage();
        window.removeEventListener('mousedown', _onMouseDown);
    }
    true;
}

function onRemoveFlash() {
    tilib_RemoveElement('panel-live-streaming');
    tilib_RemoveElement('flash-banner');
}

function onPlaySound(soundname) {
    if (soundname == "none") {
        return;
    }
    var path = "../../../flash/";
    var fullPath = path + soundname;
    if (document.getElementById("goal-sound") && $T('site').getValue('sound')) {
        document.getElementById("goal-sound").innerHTML = "<embed width=1 height=1 src='" + fullPath + ".swf'>";
    }
}

function onSoundIconClick(elem) {
    var title = $E('sound-icon');
    var isMute = 0;
    if (elem.className == 'sound-on-icon') {
        elem.className = 'sound-off-icon';
        elem.title = title['on'][1];
        isMute = 1;
        $T('site').setValue('sound', 0);
    } else {
        elem.className = 'sound-on-icon';
        elem.title = title['off'][1];
        $T('site').setValue('sound', 1);
    }
    var sb = [];
    sb.push('/');
    sb.push($T('site').getValue('lang'));
    sb.push('/rdata/sound');
    sb.push('?isMute=');
    sb.push(isMute);
    $P.sendRequest('si', sb.join(''));
}

function onDisplayBanner() {
    if (!tilib_HasFlash()) {
        tilib_RemoveElement('flash-banner');
        var e = document.getElementById('static-banner');
        if (e) {
            e.style.display = '';
        }
    } else {
        var e = document.getElementById('flash-banner');
        if (e) {
            e.style.display = '';
        }
    }
}

function onClickBanner(e, name, url, properties, type) {
    if (!e) var e = window.event;
    if (!url || url === '') {
        return false;
    }
    if (!properties) var properties = '';
    if (e.which !== undefined) {
        if (e.which === 1) {
            _bannerRedirectAction(name, url, properties, type);
        }
        return;
    }
    if (e.button !== undefined) {
        if (e.button === 1) {
            _bannerRedirectAction(name, url, properties, type);
        }
        return;
    }
}

function _bannerRedirectAction(name, url, properties, type) {
    var langPath = ($T('site').getValue('lang') === 'en') ? '' : '/' + $T('site').getValue('lang');
    switch (type) {
    case 1:
        window.open(url, name, properties);
        break;
    case 2:
        window.top.location.href = url;
        break;
    case 3:
        $P.goUrl(langPath + '/page/redirect?' + url);
        break;
    case 4:
        $P.goUrl(langPath + '/euro/' + url);
        break;
    default:
        break;
    }
}

function getDecimalNumber(val) {
    var str = '' + val;
    var ary = str.split('.');
    if (ary.length == 1) {
        return ary[0] + '.00';
    } else {
        if (ary[1].length == 1) {
            return ary[0] + '.' + ary[1] + '0';
        } else {
            var sValue = '' + parseFloat(str).toFixed(3);
            if (sValue.charAt(sValue.length - 1) == '0') {
                return sValue.substring(0, sValue.length - 1);
            } else {
                return sValue;
            }
        }
    }
}

function updateAdsURL(url) {
    var obj = GetFlashObjectByName('livevideo');
    if (obj) {
        if (obj.UpdateAdsURL) {
            obj.UpdateAdsURL(url);
        } else {
            for (var i = 0; i < obj.length; i++) {
                if (obj[i].UpdateAdsURL) {
                    obj[i].UpdateAdsURL(url);
                }
            }
        }
    }
}

function GetFlashObjectByName(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function InitLoadingAd() {
    var obj = GetFlashObjectByName('livevideo');
    if (obj) {
        var video = $M('ls').getStreamingVideoInfo();
        if (video == null || video == undefined) {
            return;
        }
        UpdateEventPeriod(video[3]);
        if (video[3] == 5 && adsEnabled) {
            getAdsURL();
        }
    }
}

function UpdateEventPeriod(period) {
    if (!adsEnabled) {
        period = 0;
    }
    var obj = GetFlashObjectByName('livevideo');
    if (obj) {
        if (obj.UpdateEventPeriod) {
            obj.UpdateEventPeriod(period);
        } else {
            for (var i = 0; i < obj.length; i++) {
                if (obj[i].UpdateEventPeriod) {
                    obj[i].UpdateEventPeriod(period);
                }
            }
        }
    }
}

function GetNewFlashVar() {
    var sb = [];
    sb.push('/');
    sb.push($T('site').getValue('lang'));
    sb.push('/data/event?ts=');
    sb.push($T('site').getValue('ts'));
    sb.push('&tk=');
    sb.push($T('od').getToken());
    sb.push('&upfv=1');
    return $P.sendRequest('lv', sb.join(''));
}

function UpdateFlashVar(flashVar) {
    var obj = GetFlashObjectByName('livevideo');
    if (obj) {
        if (obj.UpdateFlashVar) {
            obj.UpdateFlashVar(flashVar);
        } else {
            for (var i = 0; i < obj.length; i++) {
                if (obj[i].UpdateFlashVar) {
                    obj[i].UpdateFlashVar(flashVar);
                }
            }
        }
    }
}

function noMoreAds(isReload) {
    var obj = GetFlashObjectByName('livevideo');
    if (obj) {
        if (obj.noMoreAds) {
            obj.noMoreAds(isReload);
        } else {
            for (var i = 0; i < obj.length; i++) {
                if (obj[i].noMoreAds) {
                    obj[i].noMoreAds(isReload);
                }
            }
        }
    }
}

function __EuroModelTopBanner() {
    var _self = this;
    this.onClick = function (event) {
        if (!event) event = window.event;
        if (!_onClick(event)) {
            event.returnValue = false;
            return false;
        }
        return true;
    };

    function _onClick(event) {
        var e = event.srcElement ? event.srcElement : event.target;
        while (e) {
            var id = e.id;
            if (id) {
                var atom = id.split(':');
                var count = atom.length;
                if (count >= 3 && atom[0] == 'bu' && atom[1] == 'tb' && typeof ($T) != 'undefined') {
                    switch (atom[2]) {
                    case 'go':
                        if (count >= 4) {
                            switch (atom[3]) {
                            case 'land':
                                return !$M('euro').goLanding();
                            case 'ho':
                                return !$M('euro').goHome();
                            case 'casino':
                                window.open('/' + $T('site').getValue('lang') + '/page/redirect?page=casino', '_blank');
                                return false;
                            case 'rcasino':
                                _self.openRoyalCasino();
                                return false;
                            case 'racebook':
                                $P.goUrl('/' + $T('site').getValue('lang') + '/page/redirect?page=racebook&at=true');
                                return false;
                            case 'games':
                                $P.goUrl('/' + $T('site').getValue('lang') + '/page/redirect?page=games&at=true');
                                return false;
                            case 'depwith':
                                tilib_PopUp('CashTransfer', '/' + $T('site').getValue('lang') + '/page/redirect?page=deposit', {
                                    'sb': 'yes',
                                    'w': 1008,
                                    'h': 632
                                });
                                return false;
                            case 'mobile':
                                return false;
                            case 'ac':
                                _openAccount(atom[4]);
                                return false;
                            case 'lc':
                                _openLiveChat();
                                return false;
                            case 'jn':
                                _self.openJoinNow();
                                return false;
                            case 'aa':
                                _self.openAccountAssistance();
                                return false;
                            case 'result':
                                tilib_PopUp('Result', '/' + $T('site').getValue('lang') + '/page/redirect?page=result', {
                                    'sb': 'yes',
                                    'w': 790,
                                    'h': 670
                                });
                                return false;
                            case 'announcement':
                                _showNumUnreadAnnouncement('');
                                tilib_PopUp('Announcement', '/' + $T('site').getValue('lang') + '/rpage/announcement', {
                                    'sb': 'yes',
                                    'w': 850,
                                    'h': 700
                                });
                                return false;
                            }
                            return false;
                        }
                        break;
                    case 'ls':
                        if (count >= 4) {
                            $M('euro').onLanguage(atom[3]);
                            return false;
                        }
                        break;
                    case 'ud':
                        if (count >= 4) {
                            switch (atom[3]) {
                            case 'bal':
                                _onBalRefresh(true);
                                $P.sendRequest('la', '/' + $T('site').getValue('lang') + '/rdata/bet-credit?uid=' + $T('site').getValue('uid'));
                                return false;
                            }
                        }
                        return false;
                    default:
                        return false;
                        break;
                    }
                }
            }
            e = e.parentNode;
        }
        return true;
    }
    this.showNumUnreadAnnouncement = function (strCount) {
        _showNumUnreadAnnouncement(strCount);
    }

    function _showNumUnreadAnnouncement(strCount) {
        var count = document.getElementById('anm-count');
        if (!target['tb-annc']) {
            target['tb-annc'] = document.getElementById('numUnreadAnn');
        }
        if (!target['tb-annc']) {
            return;
        }
        if (strCount !== '') {
            target['tb-annc'].innerHTML = strCount;
            target['tb-annc'].className = 'one-px-bg announcement-count-body';
            count.className = 'announcement-count show';
        } else {
            target['tb-annc'].innerHTML = '';
            target['tb-annc'].className = 'Hide';
            count.className = 'Hide';
        }
    }

    function _onBalRefresh(isStartLoading) {
        if (!target['bet-credit-refresh']) {
            target['bet-credit-refresh'] = document.getElementById('bet-credit-refresh');
        }
        if (!target['bet-credit-refresh']) {
            return;
        }
        if (isStartLoading) {
            setTimeout('$M(\'tb\').onBalRefreshEnd();', 2000);
            target['bet-credit-refresh'].className = 'balance-refresh-rotate';
        } else {
            target['bet-credit-refresh'].className = 'balance-refresh';
        }
    }
    this.onBalRefreshEnd = function () {
        _onBalRefresh(false);
    };
    this.openAccount = function (item) {
        _openAccount(item);
    };

    function _openAccount(item) {
        var sb = [];
        sb.push('/');
        sb.push($T('site').getValue('lang'));
        sb.push('/');
        sb.push('account');
        if (item) {
            sb.push('/');
            sb.push(item);
        }
        var w = window.open(sb.join(''), 'account', 'scrollbars=yes,width=835,height=615');
        w.focus();
    }
    this.openJoinNow = function (event) {
        var sb = [];
        sb.push('/');
        var lang = $T('site').getValue('lang');
        if (lang != 'en') {
            sb.push(lang);
            sb.push('/');
        }
        sb.push('page/redirect?page=join-now');
        tilib_PopUp('joinnow', sb.join(''), {
            sb: 'yes',
            res: 'no',
            w: 1000,
            h: 666
        });
        if (event) {
            event.returnValue = false;
            return false;
        }
    };
    this.openAccountAssistance = function (event) {
        var sb = [];
        sb.push('/');
        var lang = $T('site').getValue('lang');
        if (lang != 'en') {
            sb.push(lang);
            sb.push('/');
        }
        sb.push('page/redirect?page=account-assistance');
        tilib_PopUp('accountassistance', sb.join(''), {
            sb: 'no',
            res: 'no',
            w: 778,
            h: 620
        });
        if (event) {
            event.returnValue = false;
            return false;
        }
    };
    this.openRoyalCasino = function (event) {
        var sb = [];
        sb.push('/');
        var lang = $T('site').getValue('lang');
        if (lang != 'en') {
            sb.push(lang);
            sb.push('/');
        }
        sb.push('page/redirect?page=rcasino');
        tilib_PopUp('royalcasino', sb.join(''), _getRoyalCasinoPopupSize());
        if (event) {
            event.returnValue = false;
            return false;
        }
    };
    this.openLiveChat = function (event) {
        _openLiveChat();
        if (event) {
            event.returnValue = false;
            return false;
        }
    };

    function _getRoyalCasinoPopupSize() {
        var userAgent = navigator.userAgent.toLowerCase();
        var widthSize = window.screen.width;
        var heightSize = window.screen.height;
        var arr = {};
        arr['res'] = 1;
        var newW;
        var newH;
        if (widthSize / heightSize > 1.5) {
            newW = widthSize * 0.82;
            newH = heightSize * 0.82;
        } else {
            newW = widthSize * 0.95;
            newH = heightSize * 0.95;
        }
        if (newW / newH > 16 / 9) {
            arr['w'] = newH * (16 / 9);
            arr['h'] = newH;
        } else {
            arr['w'] = newW;
            arr['h'] = newW * (9 / 16);
        }
        if (userAgent.indexOf('applewebkit') > -1 && userAgent.indexOf('chrome') < 0) arr['h'] -= 60;
        return arr;
    }

    function _openLiveChat() {
        var sb = [];
        sb.push('/');
        sb.push($T('site').getValue('lang'));
        sb.push('/page/live-chat');
        var w = window.open(sb.join(''), 'LiveChat', 'scrollbars=no,resizable=no,width=490,height=403');
        w.focus();
    }
    this.onShowHide = function (id, show) {
        var e = document.getElementById(id);
        if (show) {
            e.className = '';
        } else {
            e.className = 'Hide';
        }
    };
    this.onDT = function (dt) {
        if (!dt) {
            _drawDateTime();
        } else if (dt != $T('site').getValue('dt')) {
            $T('site').setValue('dt', dt);
            _drawDateTime();
        }
    };

    function _drawDateTime() {
        var t = $T('site').getValue('dt');
        var dt = new Date(parseInt(t.substring(0, 4), 10), parseInt(t.substring(4, 6), 10) - 1, parseInt(t.substring(6, 8), 10), parseInt(t.substring(8, 10), 10), parseInt(t.substring(10, 12), 10));
        var sb = [];
        var ampm = "PM";
        if ((dt.getMonth() + 1) < 10) sb.push('0');
        sb.push(dt.getMonth() + 1);
        sb.push('/');
        sb.push(dt.getDate());
        sb.push('/');
        sb.push(dt.getFullYear());
        sb.push(' ');
        var h = dt.getHours();
        if (h > 12) {
            h -= 12;
        } else if (h != 12) {
            ampm = "AM";
        }
        if (h < 10) {
            sb.push('0');
        }
        sb.push(h);
        sb.push(':');
        if (dt.getMinutes() < 10) sb.push('0');
        sb.push(dt.getMinutes());
        sb.push(' ');
        sb.push(ampm);
        sb.push(' ');
        sb.push('GMT <span onclick="$M(\'tb\').showServer()">+</span>8');
        var e = document.getElementById('serverDT');
        if (e) {
            e.innerHTML = sb.join('');
        }
    }
    this.onCaptcha = function (i) {
        var e = document.getElementById('image-captcha-' + i);
        if (e) {
            var src = e.src.split('?')[0];
            var dt = new Date();
            e.src = src + '?' + dt.getTime();
        }
    };
    this.onSignIn = function () {
        _signInForm();
    };

    function _signInAjax() {
        var sb = [];
        sb.push('id=');
        sb.push(document.getElementById("username").value);
        sb.push('&password=');
        sb.push(document.getElementById("password").value);
        sb.push('&lang=');
        sb.push($T('site').getValue('lang'));
        sb.push('&type=ajax');
        if ($T('od') && $T('od').getValue('pid')) {
            sb.push('&pid=');
            sb.push($T('od').getValue('pid'));
        }
        $P.postRequest(loginUrl, sb.join(''));
    };

    function _alertSignInError(name) {
        if (typeof (sign_in_errors) != 'undefined') {
            var error = sign_in_errors[name];
            if (error) {
                setTimeout('alert(\'' + error + '\')', 10);
            }
        }
    }

    function _signInForm() {
        var form = document.createElement('form');
        form.setAttribute('action', loginUrl);
        form.setAttribute('method', 'post');
        var value = document.getElementById('username').value;
        if (value == '') {
            _alertSignInError('username-empty');
            return;
        }
        var input = document.createElement('input');
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', 'id');
        input.setAttribute('value', value);
        form.appendChild(input);
        value = document.getElementById('password').value;
        if (value == '') {
            _alertSignInError('password-empty');
            return;
        } else if (value.length < 6) {
            _alertSignInError('password-length');
            return;
        }
        input = document.createElement('input');
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', 'password');
        input.setAttribute('value', value);
        form.appendChild(input);
        input = document.createElement('input');
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', 'lang');
        input.setAttribute('value', $T('site').getValue('lang'));
        form.appendChild(input);
        input = document.createElement('input');
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', 'tk');
        input.setAttribute('value', $T('od').getToken());
        form.appendChild(input);
        if (history.pushState) {
            input = document.createElement('input');
            input.setAttribute('type', 'hidden');
            input.setAttribute('name', '5');
            input.setAttribute('value', '1');
            form.appendChild(input);
        }
        input = document.createElement('input');
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', 'type');
        input.setAttribute('value', 'form');
        form.appendChild(input);
        input = document.createElement('input');
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', 'timestamp');
        input.setAttribute('value', $T('site').getValue('dt'));
        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
    };
    this.onRedirect = function (url, params) {
        var sb = [];
        sb.push(url);
        sb.push('?');
        sb.push(params);
        sb.push('&lang=');
        sb.push($T('site').getValue('lang'));
        sb.push('&tk=');
        sb.push($T('od').getToken());
        if (history.pushState) {
            sb.push('&5=1');
        }
        $P.goUrl(sb.join(''));
    };
    this.showServer = function () {
        alert($T('site').getValue('ser'));
    };
    this.initiateHint = function () {
        var e = document.getElementById('username');
        var hint = document.getElementById("username_hint");
        if (e) _initiateHint(e, hint);
    };
    var target = [];
    this.onUpdateCredit = function (credit) {
        if (!target['bet-credit']) {
            target['bet-credit'] = document.getElementById('bet-credit');
        }
        target['bet-credit'].innerHTML = _addCommas(credit);
    };

    function _addCommas(str) {
        str += '';
        var b = str.split(".");
        var n = b[0];
        var a = [];
        while (n.length > 3) {
            var nn = n.substr(n.length - 3);
            a.unshift(nn);
            n = n.substr(0, n.length - 3);
        }
        if (n.length > 0) {
            a.unshift(n);
        }
        n = a.join(',');
        if (b.length == 2)
            n += "." + b[1];
        return n;
    }

    function _initiateHint(e, hint) {
        e.hintText = hint.value;
        e.hasValue = false;
        e.style.color = '#888';
        e.onfocus = function () {
            if (e.value == e.hintText && !e.hasValue) {
                e.value = "";
                e.style.color = '#000';
            } else if ((navigator.userAgent.toLowerCase().indexOf('chrome') > -1)) {
                if (e.value.length > 0) {
                    e.hasValue = true;
                } else {
                    e.hasValue = false;
                }
            }
        };
        e.onblur = function () {
            if (e.value.length == 0) {
                e.value = e.hintText;
                e.style.color = '#888';
                e.hasValue = false;
            } else if (!(navigator.userAgent.toLowerCase().indexOf('chrome') > -1)) {
                e.hasValue = true;
            }
        };
    }
    this.onFocusHandler = function (fld) {
        fld.className = fld.className + ' Hide';
        var fld2 = document.getElementById('password');
        fld2.className = fld2.className.replace(/Hide/gi, '');
        fld2.focus();
        return true;
    }
    this.onBlurHandler = function (fld) {
        if (fld.value === '') {
            fld.className = fld.className + ' Hide';
            var fld2 = document.getElementById('fakePassword');
            fld2.className = fld2.className.replace(/Hide/gi, '');
        }
        return true;
    }
    this.onFocusUsername = function () {
        var e = document.getElementById('username');
        if (e) {
            if (e.value == '') {
                e.focus();
            }
        }
    }
}
var loginUrl;

function setLoginURL(url) {
    loginUrl = url;
}

function clearLogin() {}
$P.setModel('tb', new __EuroModelTopBanner());

function labelObj(lObj, lText, iObj) {
    var labelObj = lObj;
    var labelName = lText;
    var inputObj = iObj;
    this.isInputEmpty = function () {
        if (inputObj.value == '') {
            labelObj.className = 'FormTextF';
        }
    }
    this.reDraw = function () {
        if (inputObj.value == '') {
            labelObj.innerHTML = labelName;
            labelObj.className = 'FormTextN';
        }
    }
    this.hideOnChange = function () {
        labelObj.innerHTML = '';
    }
};

function getEventSource(event) {
    if (!event) event = window.event;
    return event.srcElement ? event.srcElement : event.target;
};
var lObjs = {};

function initLabels() {
    var labels = document.getElementsByTagName("label");
    for (var i = 0; i < labels.length; i++) {
        var label = labels[i];
        var id = label.attributes["for"].value;
        if (id) {
            var input = document.getElementById(id);
            if (input) {
                lObjs[input.id] = new labelObj(label, label.innerHTML, input);
                input.onblur = function (event) {
                    var e = getEventSource(event);
                    if (e) {
                        lObjs[e.id].reDraw();
                    }
                };
                input.onfocus = function (event) {
                    var e = getEventSource(event);
                    if (e) {
                        lObjs[e.id].isInputEmpty();
                    }
                };
                input.ondblclick = function (event) {
                    var e = getEventSource(event);
                    if (e) {
                        lObjs[e.id].hideOnChange();
                    }
                }
                input.onkeypress = function (event) {
                    var e = getEventSource(event);
                    if (e) {
                        lObjs[e.id].hideOnChange();
                    }
                };
                input.onkeydown = function (e) {
                    var evt = window.event ? event : e;
                    var keyCode = (evt.which) ? evt.which : evt.keyCode;
                    if (keyCode == 86 && evt.ctrlKey == 1) {
                        e = getEventSource(e);
                        lObjs[e.id].hideOnChange();
                    }
                    if (keyCode == 13) {
                        $M('tb').onSignIn()
                    };
                };
            }
        }
    }
}

function setInitCategory() {
    var category = tilib_GetQueryParams()['category'];
    if (category) {
        changeCategory(category);
    }
}

function changeCategory(catId) {
    var div = document.getElementById(catId);
    if (div) {
        try {
            div.style.display = 'block';
        } catch (e) {
            div.setAttribute('style', 'display:block');
        }
        div = document.getElementById(currentShow);
        if (currentShow != null && currentShow != catId) {
            if (div) {
                try {
                    div.style.display = 'none';
                } catch (e) {
                    div.setAttribute('style', 'display:none');
                }
            }
            div = document.getElementById(currentShow + '_tr');
            if (div) {
                div.className = "";
            }
        }
        currentShow = catId;
    }
    var aDiv = document.getElementById(catId + '_tr');
    div = document.getElementById('category_name')
    if (aDiv && div) {
        div.innerHTML = aDiv.innerHTML;
        aDiv.className = "Sel";
    }
}

function onClick(event) {
    var e = event.srcElement ? event.srcElement : event.target;
    while (e) {
        var id = e.id;
        if (id) {
            var atom = id.split(':');
            var count = atom.length;
            if (count >= 4 && atom[0] == 'bu') {
                switch (atom[1]) {
                case 'go':
                    MM_openBrWindow('/web/public/game-pff.aspx?id=' + atom[2] + '&pff=' + atom[3] + '&gameName=' + atom[4] + '&gameCategory=' + atom[5], 'play', 'scrollbars=no,resizable=no,width=955,height=623');
                    return false;
                default:
                    return false;
                }
            }
        }
        e = e.parentNode;
    }
    return true;
}

function __EuroModelFavourites() {
    var _translation = $P.getTranslation('fa');
    var _template = tilib_GenerateTemplates($P.getTemplate('fa'));
    var _elemTranslation = $E('translation');
    var _token = new tilib_Token(['ts', 'ever', 'fver'], [$T('site').getValue('ts'), 0, 0]);
    var _editMode = false;
    var _syn = {
        cooldownCount: 0,
        refreshRate: 60
    };
    var _favouritesSortedAry = [];
    var _favouritesData = {};
    var _maxOrder = 0;

    function _getUrl(action, key) {
        var sb = [];
        sb.push('/');
        sb.push($T('site').getValue('lang'));
        sb.push('/data/favourite');
        sb.push('?tk=');
        sb.push(_token.getToken());
        sb.push('&act=');
        sb.push(action);
        if (key) {
            sb.push('-');
            sb.push(key);
        }
        sb.push('&uid=');
        sb.push($T('site').getValue('uid'));
        return sb.join('');
    }

    function _initialize(items) {
        if (!items) {
            return;
        }
        var maxObj = items.length;
        var fdata = [];
        for (var i = 0; i < maxObj; i++) {
            if (!items[i]) {
                continue;
            }
            var item = items[i];
            var key = item[1] + '-' + item[2];
            fdata[key] = item;
        }
        _favouritesData = fdata;
        _normalizeData()
        _syn.cooldownCount = _syn.refreshRate;
    }

    function _normalizeData() {
        var sortedAry = [];
        var data = _favouritesData;
        if (!data) {
            return;
        }
        for (var key in data) {
            var fData = data[key];
            sortedAry.push(fData);
        }
        if (sortedAry && sortedAry.length > 0) {
            sortedAry.sort(_sortFavouriteCallback);
        }
        _favouritesSortedAry = sortedAry;
    }

    function _sortFavouriteCallback(f1, f2) {
        var oid1 = f1[5];
        var oid2 = f2[5];
        return (oid1 < oid2) ? -1 : 1;
    }

    function _getNewMaxOrderID() {
        var favData = _favouritesData;
        if (!favData) {
            return 1;
        }
        var maxOrdId = 0;
        var tempData;
        for (var key in favData) {
            tempData = favData[key];
            if (tempData) {
                if (tempData[3] > maxOrdId) {
                    maxOrdId = tempData[3];
                }
            }
        }
        return ++maxOrdId;
    }
    this.onTime = function () {
        if (!$T('site').getValue('asi')) {
            return;
        }
        if (_syn.cooldownCount) {
            _syn.cooldownCount--;
        } else {
            _draw();
            _syn.cooldownCount = _syn.refreshRate;
        }
    }
    this.onAddResponse = function (newFav) {
        if ($T('site').getValue('asi')) {
            if (!newFav) {
                return;
            }
            var favData = _favouritesData;
            var key = newFav[1] + '-' + newFav[2];
            if (!favData[key]) {
                var maxID = _getNewMaxOrderID();
                newFav[3] = maxID;
                newFav[5] = maxID;
                favData[key] = newFav;
                _favouritesData = favData;
                _normalizeData();
                _draw();
            }
        }
    }
    this.add = function (type, id) {
        if ($T('site').getValue('asi')) {
            var key = type + '-' + id;
            if (!_favouritesData[key]) {
                $P.sendRequest('fa', _getUrl('a', key));
            }
        }
    };
    this.remove = function (type, id) {
        if ($T('site').getValue('asi')) {
            var key = type + '-' + id;
            var item = _favouritesData[key];
            if (item && item[2]) {
                $P.sendRequest('fa', _getUrl('r', key));
            }
        }
    };
    this.onRemove = function (key) {
        var item = _favouritesData[key];
        if (item && item[3]) {
            this.onRemoveClick(key, true);
        }
    };
    this.onRemoveClick = function (key, isResponse) {
        var favData = _favouritesData;
        var item = favData[key];
        var m = $M('od');
        if (m && m.onFavouriteSelected && item) {
            m.onFavouriteSelected(item[1], item[2], false);
            if (isResponse) {
                delete favData[key];
            } else {
                if (favData[key]) {
                    favData[key][6] = 0;
                }
            }
            _favouritesData = favData;
            _normalizeData();
            _draw();
        }
    };
    this.go = function (type, id, tid, home, away) {
        var key = type + '-' + id;
        switch (type) {
        case 'to':
            $M('euro').goTournament(id, 1, 3);
            break;
        case 'ev':
            $M('od').goFavEvent(tid, id, home, away);
            break;
        }
    }
    this.onInit = function (d) {
        if ($T('site').getValue('asi')) {
            if (d) {
                var ever = d[0];
                if (ever) _token.setValue('ever', ever);
                var fver = d[1];
                if (fver) _token.setValue('fver', fver);
                _initialize(d[3]);
            }
            _draw();
        } else {
            _initialize(d[3]);
            _draw();
        }
    };
    this.onSave = function () {
        var sb = [];
        _normalizeData();
        var sortedFav = _favouritesSortedAry;
        if (!sortedFav) {
            this.onUpdateComplete();
            return;
        }
        sb.push('&dat=');
        for (var i = 0; i < sortedFav.length; i++) {
            var item = sortedFav[i];
            if (item && item[6] == 1) {
                var dat = _getType(item[1]) + ':' + item[2] + ',';
                sb.push(dat);
            }
        }
        $P.sendRequest('fa', _getUrl('s') + sb.join(''));
    };
    this.onUpdateComplete = function () {
        _editMode = false;
        var favData = _favouritesData;
        if (favData) {
            var favItem;
            for (var key in favData) {
                favItem = favData[key];
                if (favItem) {
                    if (favItem[6] == 0) {
                        delete favData[key];
                        continue;
                    }
                    favItem[3] = favItem[5];
                    favData[key] = favItem;
                }
            }
            _favouritesData = favData;
        }
        _normalizeData();
        _draw();
        if (_translation) {
            alert(_translation['update-success']);
        }
    };
    this.onDraw = function () {
        _draw();
    };
    this.onLoad = function () {
        $P.sendRequest('fa', _getUrl('g'));
    };
    this.onMoveUp = function (key) {
        var favData = _favouritesData;
        var cItem = favData[key];
        if (!cItem) {
            return;
        }
        _normalizeData();
        var sortedData = _favouritesSortedAry;
        var sItem;
        for (var i = 0; i < sortedData.length; i++) {
            sItem = sortedData[i];
            if (sItem[1] == cItem[1] && cItem[2] == sItem[2]) {
                sItem = sortedData[i - 1];
                break;
            }
        }
        var tempOrderId = cItem[5];
        cItem[5] = sItem[5];
        sItem[5] = tempOrderId;
        favData[key] = cItem;
        key = sItem[1] + '-' + sItem[2];
        favData[key] = sItem;
        _favouritesData = favData;
        _normalizeData();
        _draw();
    };
    this.onEditClick = function () {
        if (!_editMode) {
            _editMode = true;
        } else {
            _editMode = false;
        }
        _draw();
    };
    this.onCancelClick = function () {
        var favData = _favouritesData;
        if (favData) {
            var favItem;
            for (var key in favData) {
                favItem = favData[key];
                if (favItem) {
                    favItem[5] = favItem[3];
                    favItem[6] = 1;
                    favData[key] = favItem;
                }
            }
            _favouritesData = favData;
        }
        _editMode = false;
        _normalizeData();
        _draw();
    };
    this.isFavouriteSelected = function (type, id) {
        if (id) {
            var key = type + '-' + id;
            var favData = _favouritesData;
            if (favData && favData[key] && favData[key][6] == 1) {
                return true;
            }
        }
        return false;
    };
    this.onClick = function (event) {
        if ($T('site').getValue('seo')) return true;
        if (!event) event = window.event;
        var e = event.srcElement ? event.srcElement : event.target;
        while (e) {
            var id = e.id;
            if (id) {
                var atom = id.split(':');
                var count = atom.length;
                if (count >= 3 && atom[0] == 'bu' && atom[1] == 'fa') {
                    switch (atom[2]) {
                    case 'to':
                        if (count >= 4) {
                            $M('euro').goTournament(atom[3], 1, 3);
                            return false;
                        }
                        break;
                    default:
                        return false;
                        break;
                    }
                }
            }
            e = e.parentNode;
        }
        return true;
    };

    function _draw() {
        var e = document.getElementById('favourites');
        if (e) {
            var sb = [];
            var d = {};
            var t = _template['fv-item'];
            var tua = _template['fv-item-up-arrow'];
            var tr = _template['fv-item-remove'];
            var tea = _template['fv-edit-area'];
            var feb = _template['fv-edit-btn'];
            var tev = _template['fv-item-event'];
            var c = _favouritesSortedAry.length;
            var first = true;
            for (var i = 0; i < c; ++i) {
                var item = _favouritesSortedAry[i];
                if (item) {
                    if (item[6] == 0) {
                        continue;
                    }
                    d['s-id'] = item[0];
                    d['type'] = item[1];
                    d['id'] = item[2];
                    d['href'] = 'javascript:void(0);';
                    d['count'] = '(0)';
                    var cnt = _getTournamentCount(item[0], item[2]);
                    if (item[1] == 'to' && cnt) {
                        d['count'] = '(' + cnt + ')';
                    }
                    if (item[1] == 'ev') {
                        d['count'] = '';
                    }
                    d['remove'] = '';
                    if ($T('site').getValue('asi') && _editMode) {
                        d['remove'] = tr.getText(d);
                    }
                    d['up-arrow'] = '';
                    if (first) {
                        first = false;
                    } else {
                        if ($T('site').getValue('asi') && _editMode) {
                            d['up-arrow'] = tua.getText(d);
                        }
                    }
                    if (item[1] == 'ev') {
                        var einfo = item[4];
                        if (einfo && einfo[0] && einfo[1]) {
                            d['name'] = einfo[0] + ' ' + _elemTranslation['vs'][1] + ' ' + einfo[1];
                            d['name'] = _unescape(d['name']);
                            d['home'] = einfo[0];
                            d['away'] = einfo[1];
                            if (einfo[2]) {
                                d['tid'] = einfo[2];
                            }
                        }
                    } else {
                        d['name'] = _unescape(item[4]);
                    }
                    if (item[1] == 'ev') {
                        sb.push(tev.getText(d));
                    } else {
                        sb.push(t.getText(d));
                    }
                }
            }
            d['ep-cls'] = 'Hide';
            if (_editMode) {
                d['ep-cls'] = 'TAC';
            }
            d['fv-edit-btn'] = '';
            if ($T('site').getValue('asi')) {
                if (_editMode) {
                    d['cls-hide'] = 'Hide';
                }
                d['fv-edit-btn'] = feb.getText(d);
            }
            d['edit'] = tea.getText(d);
            d['items'] = sb.join('');
            d['InfoSiteDomain'] = $T('site').getValue('info-site-domain');
            e.innerHTML = _template['favourites'].getText(d);
            var m = $M('od');
            if (m && m.onDraw) {
                m.onDraw();
            }
        }
    }

    function _unescape(str) {
        str = str.replace(/\\([^u])/g, "$1");
        return str;
    }

    function _getTournamentCount(sid, tid) {
        var te = $E('tournaments')[tid];
        if (te) {
            return te[5];
        }
        return 0;
    }

    function _getType(t) {
        switch (t) {
        case 'to':
            return 1;
        case 'ev':
            return 2;
        }
    }
}

function __EuroModelMenuSports(sportOrder) {
    var _self = this;
    var _template = tilib_GenerateTemplates($P.getTemplate('ms'));
    var _sportOrder = sportOrder;
    var _state = {};
    var _cache = [];

    function _sortRegionCallback(r1, r2) {
        var re1 = r1[0];
        var re2 = r2[0];
        var ro1 = r1[3];
        var ro2 = r2[3];
        var r = 0;
        if (ro1 && ro2) {
            if (ro1 != ro2) {
                r = (ro1 < ro2) ? -1 : 1;
            }
        } else if (ro1) {
            r = -1;
        } else if (ro2) {
            r = 1;
        }
        if (!r) {
            r = tilib_CompareString(re1[1].toLowerCase(), re2[1].toLowerCase());
        }
        return r;
    }

    function _sortTournamentCallback(te1, te2) {
        var r = tilib_CompareString(te1[4], te2[4]);
        if (!r) {
            r = tilib_CompareString(te1[1].toLowerCase(), te2[1].toLowerCase());
        }
        return r;
    }

    function _normalize() {
        var ses = $E('sports');
        var res = $E('regions');
        var sroes = $E('sports-regions-orders');
        var tes = $E('tournaments');
        var crid = $T('site').getValue('rid');
        _cache = {};
        for (var tid in tes) {
            var te = tes[tid];
            if (!te) continue;
            if (!te[4]) continue;
            var sid = te[2];
            var se = ses[sid];
            if (!se) continue;
            var rid = te[3];
            var re = res[rid];
            if (!re) continue;
            var s = _cache[sid];
            if (!s) {
                sroes[sid + '-' + crid] = [sid + '-' + crid, -1];
                _cache[sid] = s = [se];
            }
            var rs = s[1];
            if (!rs) {
                s[1] = rs = {};
            }
            var r = rs[rid];
            if (!r) {
                var sroe = sroes[sid + '-' + rid];
                if (sroe) {
                    r = [re, null, null, sroe[1]];
                } else {
                    r = [re];
                }
                rs[rid] = r;
            }
            var ts = r[1];
            if (!ts) {
                r[1] = ts = {};
            }
            if (te[5]) {
                ts[tid] = te;
            }
            if (te[7]) {
                if (r[4]) {
                    r[4] += 1;
                } else {
                    r[4] = 1;
                }
            }
            if (te[8]) {
                if (r[5]) {
                    r[5] += 1;
                } else {
                    r[5] = 1;
                }
                if (te[7] != te[8]) {
                    if (r[4]) {
                        r[4] += 1;
                    } else {
                        r[4] = 1;
                    }
                }
            }
        }
        var iss = [];
        for (sid in _cache) {
            s = _cache[sid];
            iss.push(s);
            rs = s[1];
            if (rs) {
                var irs = [];
                for (rid in rs) {
                    r = rs[rid];
                    irs.push(r);
                    ts = r[1];
                    if (ts) {
                        var its = [];
                        for (tid in ts) {
                            te = ts[tid];
                            its.push(te);
                        }
                        its.sort(_sortTournamentCallback);
                        r[2] = its;
                    }
                }
                irs.sort(_sortRegionCallback);
                s[2] = irs;
            }
        }
    }
    this.onOddsDrawed = function () {
        _state['odds-drawed'] = true;
    };
    this.onUpdate = function () {
        _normalize();
        _draw();
    };
    this.onSwitch = function (target) {
        var ms = [];
        ms['sports'] = document.getElementById('ms-sports');
        ms['all'] = document.getElementById('ms-all');
        ms['live'] = document.getElementById('ms-live');
        ms['live-noevents'] = document.getElementById('ms-live-noevents');
        if (target == 'live') {
            ms['sports'].className = ms['sports'].className.replace('All', 'Live');
            ms['all'].className = 'Hide';
            if (ms['live'].innerHTML.length > 0) {
                ms['live'].className = '';
                ms['live-noevents'].className = 'Hide';
            } else {
                ms['live'].className = 'Hide';
                ms['live-noevents'].className = '';
            }
        } else {
            ms['sports'].className = ms['sports'].className.replace('Live', 'All');
            ms['all'].className = '';
            ms['live'].className = 'Hide';
            ms['live-noevents'].className = 'Hide';
        }
        _state['select-ms'] = target;
    };
    this.onClick = function (event) {
        if (!event) event = window.event;
        g_MenuSportFireEvent = true;
        if (!_onClick(event)) {
            g_MenuSportFireEvent = false;
            event.returnValue = false;
            return false;
        }
        g_MenuSportFireEvent = false;
        return true;
    };

    function _onClick(event) {
        if (!event) event = window.event;
        var e = event.srcElement ? event.srcElement : event.target;
        while (e) {
            var id = e.id;
            e = e.parentNode;
            if (!id) continue;
            var atom = id.split(':');
            var count = atom.length;
            if (count >= 3 && atom[0] == 'bu' && atom[1] == 'ms') {
                if (atom[2] == 'mre') {
                    if (count >= 4) {
                        sid = atom[3];
                        var resu = document.getElementById('ms-all-res-ul-' + sid);
                        if (resu) {
                            key = 'more-' + sid;
                            if (_state[key]) {
                                _state[key] = 0;
                                resu.className = 'MoreRegHide';
                            } else {
                                _state[key] = 1;
                                resu.className = '';
                            }
                        }
                        return false;
                    }
                } else if (atom[2] == 'tg') {
                    if (count >= 5) {
                        _self.onToggleMenu(atom[3], atom[4]);
                        return false;
                    }
                } else {
                    if ($T('site').getValue('seo')) return true;
                    switch (atom[2]) {
                    case 'al':
                        if (count >= 4) {
                            _self.onSwitch(atom[3]);
                            return false;
                        }
                        break;
                    case 'lb':
                        if (count >= 4) {
                            $T('od').setValue('sid', atom[3]);
                        }
                        return !$M('euro').goLiveBetting();
                    case 'mp':
                        return !$M('euro').goMixParlay();
                    case 'all-be':
                        if ($M('euro').goBigEvent(0, 1)) {
                            _toggleBigEvent('all');
                            return false;
                        }
                        break;
                    case 'all-ee':
                        if ($M('euro').goEufaEuroEvent(0, 1)) {
                            _toggleEufaEuroEvent('all');
                            return false;
                        }
                        break;
                    case 'live-be':
                        if ($M('euro').goLiveBigEvent()) {
                            _toggleBigEvent('live');
                            return false;
                        }
                    case 'live-ee':
                        if ($M('euro').goLiveEufaEuroEvent()) {
                            _toggleEufaEuroEvent('live');
                            return false;
                        }
                    case 'all-sp':
                        if (count >= 4) {
                            var sid = atom[3];
                            if ($M('euro').goSport(sid, 1, 3)) {
                                _toggleSport('all', sid);
                            }
                            return false;
                        }
                        break;
                    case 'all-be-sp':
                        if (count >= 4) {
                            var sid = atom[3];
                            if ($M('euro').goBigEventSport(sid, 1, 3)) {
                                _toggleSport('all-be', sid);
                            }
                            return false;
                        }
                        break;
                    case 'live-sp':
                        if (count >= 4) {
                            sid = atom[3];
                            if ($M('euro').goLiveSport(sid)) {
                                _toggleSport('live', sid);
                            }
                            return false;
                        }
                        break;
                    case 'live-be-sp':
                        if (count >= 4) {
                            sid = atom[3];
                            if ($M('euro').goLiveBigEventSport(sid)) {
                                _toggleSport('live-be', sid);
                            }
                            return false;
                        }
                        break;
                    case 'all-re':
                        if (count >= 5) {
                            sid = atom[3];
                            var rid = atom[4];
                            if ($M('euro').goRegion(sid, rid, 1, 3)) {
                                _toggleRegion('all', sid, rid);
                            }
                            return false;
                        }
                        break;
                    case 'live-re':
                        if (count >= 5) {
                            sid = atom[3];
                            rid = atom[4];
                            if ($M('euro').goLiveRegion(sid, rid, 1, 3)) {
                                _toggleRegion('live', sid, rid);
                            }
                            return false;
                        }
                        break;
                    case 'all-to':
                        if (count >= 4) {
                            var tid = atom[3];
                            if ($M('euro').goTournament(tid, 1, 3)) {
                                _toggleTournament('all', tid);
                            }
                            return false;
                        }
                        break;
                    case 'all-be-to':
                        if (count >= 4) {
                            var tid = atom[3];
                            if ($M('euro').goBigEventTournament(tid, 1, 3)) {
                                _toggleTournament('all-be', tid);
                            }
                            return false;
                        }
                        break;
                    case 'all-ee-to':
                        if (count >= 4) {
                            var tid = atom[3];
                            if ($M('euro').goEufaEuroEventTournament(tid, 1, 3)) {
                                _toggleTournament('all-ee', tid);
                            }
                            return false;
                        }
                        break;
                    case 'live-to':
                        if (count >= 4) {
                            var tid = atom[3];
                            if ($M('euro').goLiveTournament(tid, 1, 3)) {
                                _toggleTournament('live', tid);
                            }
                            return false;
                        }
                        break;
                    case 'live-be-to':
                        if (count >= 4) {
                            var tid = atom[3];
                            if ($M('euro').goLiveBigEventTournament(tid, 1, 3)) {
                                _toggleTournament('live-be', tid);
                            }
                            return false;
                        }
                        break;
                    case 'live-ee-to':
                        if (count >= 4) {
                            var tid = atom[3];
                            if ($M('euro').goLiveEufaEuroEventTournament(tid, 1, 3)) {
                                _toggleTournament('live-ee', tid);
                            }
                            return false;
                        }
                        break;
                    case 'all-or':
                        if (count >= 5) {
                            var sid = atom[3];
                            var rid = atom[4];
                            if ($M('euro').goOutright(sid, rid, 1)) {
                                _toggleOutright('all', sid, rid);
                            }
                            return false;
                        }
                        break;
                    case 'all-be-or':
                        if (count >= 5) {
                            var sid = atom[3];
                            var rid = atom[4];
                            if ($M('euro').goBigEventOutright(sid, rid, 1)) {
                                _toggleOutright('all-be', sid, rid);
                            }
                            return false;
                        }
                        break;
                    case 'all-ee-or':
                        if (count >= 5) {
                            var sid = atom[3];
                            var rid = atom[4];
                            if ($M('euro').goEufaEuroOutright(sid, rid, 1)) {
                                _toggleOutright('all-ee', sid, rid);
                            }
                            return false;
                        }
                        break;
                    case 'live-or':
                        if (count >= 5) {
                            var sid = atom[3];
                            var rid = atom[4];
                            if ($M('euro').goLiveOutright(sid, rid, 1)) {
                                _toggleOutright('live', sid, rid);
                            }
                            return false;
                        }
                        break;
                    case 'live-be-or':
                        if (count >= 5) {
                            var sid = atom[3];
                            var rid = atom[4];
                            if ($M('euro').goLiveBigEventOutright(sid, rid, 1)) {
                                _toggleOutright('live-be', sid, rid);
                            }
                            return false;
                        }
                        break;
                    case 'live-ee-or':
                        if (count >= 5) {
                            var sid = atom[3];
                            var rid = atom[4];
                            if ($M('euro').goLiveEufaEuroOutright(sid, rid, 1)) {
                                _toggleOutright('live-ee', sid, rid);
                            }
                            return false;
                        }
                        break;
                    default:
                        return false;
                        break;
                    }
                }
            }
        }
        return true;
    };
    this.onToggleMenu = function (epanel, ebody) {
        var p = document.getElementById(epanel);
        if (p && p.className.indexOf('Open') > 0) {
            p.className = p.className.replace('Open', 'Closed');
        } else {
            p.className = p.className.replace('Closed', 'Open');
        }
    };

    function _toggleEufaEuroEvent(section) {
        var be = document.getElementById('ms-' + section + '-ee-tos');
        if (be) {
            _unselectTournament();
            if (_isEufaEuroEventExpanded(section)) {
                _setEufaEuroEventExpanded(section, false);
                be.className += ' Hide';
            } else {
                _setEufaEuroEventExpanded(section, true);
                be.className = be.className.replace(/Hide/gi, '');
            }
        }
    }

    function _toggleBigEvent(section) {
        var be = document.getElementById('ms-' + section + '-be');
        var sps = document.getElementById('ms-' + section + '-be-sps');
        if (be && sps) {
            _unselectTournament();
            if (_isBigEventExpanded(section)) {
                _setBigEventExpanded(section, false);
                be.className = '';
                sps.className = 'Hide';
            } else {
                _setBigEventExpanded(section, true);
                be.className = 'SptSel';
                sps.className = '';
            }
        }
    }

    function _toggleSport(section, sid) {
        var sp = document.getElementById('ms-' + section + '-sp-' + sid);
        var res = document.getElementById('ms-' + section + '-res-' + sid);
        var tos = document.getElementById('ms-' + section + '-tos-' + sid);
        if (sp && (res || tos)) {
            _unselectTournament();
            _setSelectedSport(section, sid);
            if (_isSportExpanded(section, sid)) {
                _setSportExpanded(section, sid, false);
                if (res) {
                    sp.className = '';
                    res.className = 'Hide';
                } else if (tos) {
                    sp.className = 'Unsel';
                    tos.className = 'Hide';
                }
            } else if (_cache[sid]) {
                _setSportExpanded(section, sid, true);
                if (res) {
                    sp.className = 'SptSel';
                    res.className = '';
                } else if (tos) {
                    sp.className = 'Sel';
                    tos.className = '';
                }
            }
        }
    }

    function _toggleRegion(section, sid, rid) {
        var re = document.getElementById('ms-' + section + '-re-' + sid + '-' + rid);
        var tos = document.getElementById('ms-' + section + '-tos-' + sid + '-' + rid);
        if (re && tos) {
            var sroes = $E('sports-regions-orders');
            _unselectTournament();
            _setSelectedRegion(section, sid, rid);
            if (_isRegionExpanded(section, sid, rid)) {
                _setRegionExpanded(section, sid, rid, false);
                re.className = 'Unsel' + ((section != 'all' || sroes[sid + '-' + rid]) ? '' : ' More');
                tos.className = 'Hide';
            } else {
                _setRegionExpanded(section, sid, rid, true);
                re.className = 'Sel' + ((section != 'all' || sroes[sid + '-' + rid]) ? '' : ' More');
                tos.className = '';
            }
        }
    }

    function _toggleTournament(section, tid) {
        var to = document.getElementById('ms-' + section + '-to-' + tid);
        if (to) {
            _unselectTournament();
            _setSelectedTournament(section, tid);
            to.className = 'Sel';
        }
    }

    function _toggleOutright(section, sid, rid) {
        var or = document.getElementById('ms-' + section + '-or-' + sid + '-' + rid);
        if (or) {
            _unselectTournament();
            _setSelectedOutright(section, sid, rid);
            or.className = 'Sel';
        }
    }

    function _unselectTournament() {
        _doUnselectTournament('all');
        _doUnselectTournament('all-be');
        _doUnselectTournament('all-ee');
        _doUnselectTournament('live');
        _doUnselectTournament('live-be');
        _doUnselectTournament('live-ee');
    }

    function _doUnselectTournament(section) {
        var stid = _getSelectedTournament(section);
        if (stid) {
            var sto = (stid == 'outright') ? document.getElementById('ms-' + section + '-or-' + _getSelectedSport(section) + '-' + _getSelectedRegion(section)) : document.getElementById('ms-' + section + '-to-' + stid);
            if (sto) {
                sto.className = '';
            }
            _setSelectedTournament(section, 0);
        }
    }

    function _draw() {
        _state['ms-s'] = 'all';
        var e = document.getElementById('menu-sports');
        if (e) {
            e.innerHTML = _getContentSports();
        }
        e = document.getElementById('panel-mixparlay');
        if (e) {
            e.innerHTML = _getContentButtons();
        }
    }
    this.onDrawMP = function () {
        var e = document.getElementById('panel-mixparlay');
        if (e) {
            e.innerHTML = _getContentButtons();
        }
    };

    function _getContentButtons() {
        var pes = $E('pages');
        var ses = $E('sports');
        var count = 0;
        for (var sid in ses) {
            var se = ses[sid];
            if (!se || !se[4]) continue;
            count += se[4];
        }
        var d = {};
        d['url-base'] = $M('euro').getEuroUrlBase();
        if (!($T('site').getValue('seo') || history.pushState)) {
            d['url-hash'] = '#!/';
        }
        var sb = [];
        if (count >= 2) {
            pe = pes[30];
            d['mp-displayname'] = pe[1];
            d['mp-codename'] = $Code(pe[1]);
            d['mp-eventcount'] = count;
            sb.push(_template['mixparlay'].getText(d));
        }
        return sb.join('');
    }

    function _getContentSports() {
        var d = {};
        d['url-base'] = $M('euro').getEuroUrlBase();
        if (!($T('site').getValue('seo') || history.pushState)) {
            d['url-hash'] = '#!/';
        }
        var pe = $E('pages')[20];
        d['lb-displayname'] = pe[1];
        d['lb-codename'] = $Code(pe[1]);
        pe = $E('pages')[14];
        d['or-displayname'] = pe[1];
        d['or-codename'] = $Code(pe[1]);
        var ses = $E('sports');
        var asi = $T('site').getValue('asi');
        var assb = [];
        var lssb = [];
        var sc = _sportOrder.length;
        for (var si = 0; si < sc; ++si) {
            var sid = _sportOrder[si];
            if (sid == 11) continue;
            if (sid == 25 && $T('site').getValue('bigevent-rid')) continue;
            _populateSport(d, 'all', sid, assb);
            _populateSport(d, 'live', sid, lssb);
        }
        ms = _state['selected-ms'];
        var pid = $T('od').getValue('pid');
        if (ms == 'live' || (ms === undefined && ((pid >= 20 && pid <= 25) || (pid >= 50 && pid <= 55) || (pid >= 70 && pid <= 75)))) {
            d['class-mss'] = 'Live';
            d['class-msa'] = 'Hide';
            if (lssb.length > 0) {
                d['class-msl'] = '';
                d['class-msl-noevents'] = 'Hide';
            } else {
                d['class-msl'] = 'Hide';
                d['class-msl-noevents'] = '';
            }
        } else {
            d['class-mss'] = 'All';
            d['class-msa'] = '';
            d['class-msl'] = 'Hide';
            d['class-msl-noevents'] = 'Hide';
        }
        d['all-bigevent'] = _getBigEvent(d, 'all');
        d['live-bigevent'] = _getBigEvent(d, 'live');
        d['all-eufaeuro'] = _getEufaEuro(d, 'all');
        d['live-eufaeuro'] = _getEufaEuro(d, 'live');
        d['live-sports'] = lssb.join('');
        d['all-sports'] = assb.join('');
        return _template['sports'].getText(d);
    }

    function _populateSport(d, section, sid, ssb) {
        var se = $E('sports')[sid];
        if (!se) return;
        var displayZero = (section == 'all' && !$T('site').getValue('asi')) ? true : false;
        d['s-id'] = sid;
        d['s-displayname'] = se[1];
        d['s-codename'] = $Code(se[1]);
        d['s-eventcount'] = (section == 'live') ? se[3] : se[2];
        if (d['s-eventcount'] <= 0 && !displayZero) {
            return;
        }
        var rsb = [];
        var s = _cache[sid];
        if (s) {
            var irs = s[2];
            var rc = irs.length;
            var inmore = false;
            for (var ri = 0; ri < rc; ++ri) {
                var r = irs[ri];
                if (!r) continue;
                if (_populateRegion(d, section, sid, r, rsb, inmore)) {
                    inmore = true;
                }
            }
        }
        d['class-rs-ul'] = (_state['more-' + sid] || section != 'all') ? null : ' MoreRegHide';
        if (_isSportSelected(section, sid)) {
            _setSelectedSport(section, sid);
        }
        if (_isSportExpanded(section, sid) && rsb.length > 0) {
            d['class-s'] = 'SptSel';
            d['class-rs'] = 'SptSel';
            _setSportExpanded(section, sid, true);
        } else {
            d['class-s'] = '';
            d['class-rs'] = 'Hide';
            _setSportExpanded(section, sid, false);
        }
        d['regions'] = rsb.join('');
        ssb.push(_template['ms-' + section + '-sport'].getText(d));
    }

    function _populateRegion(d, section, sid, r, rsb, inmore) {
        if (!r) return inmore;
        var re = r[0];
        if (!re) return inmore;
        var rid = re[0];
        d['r-id'] = rid;
        d['r-displayname'] = re[1];
        d['r-codename'] = $Code(re[1]);
        var its = r[2];
        if (!its) return inmore;
        var tsb = [];
        var tc = its.length;
        var counter = {};
        counter[0] = 0;
        for (var ti = 0; ti < tc; ++ti) {
            var te = its[ti];
            if (!te) continue;
            _populateTournament(d, section, te, tsb, counter);
        }
        var srid = sid + '-' + rid;
        var orcnt = (section == 'live') ? r[5] : r[4];
        d['or-eventcount'] = orcnt;
        if (d['or-eventcount']) {
            var orid = sid + '-' + rid;
            if (_isOutrightSelected(section, sid, rid)) {
                d['class-or'] = 'Sel';
                _setSelectedOutright(section, sid, rid);
            } else {
                d['class-or'] = null;
            }
            tsb.push(_template['ms-' + section + '-outright'].getText(d));
        }
        counter[0] = orcnt ? counter[0] + parseInt(orcnt, 10) : counter[0];
        d['eventcount'] = counter[0];
        if (tsb.length > 0) {
            var more = '';
            if (section == 'all') {
                var sroes = $E('sports-regions-orders');
                if (!sroes[sid + '-' + rid]) {
                    more = ' More';
                    if (!inmore) {
                        inmore = true;
                        rsb.push(_template['ms-region-more'].getText(d));
                    }
                }
            }
            if (_isRegionSelected(section, sid, rid)) {
                _setSelectedRegion(section, sid, rid);
            }
            if (_isRegionExpanded(section, sid, rid)) {
                d['class-r'] = 'Sel' + more;
                d['class-ts'] = null;
                if (more != '' && _state['more-' + sid] === undefined) {
                    _state['more-' + sid] = true;
                }
                _setRegionExpanded(section, sid, rid, true);
            } else {
                d['class-r'] = 'Unsel' + more;
                d['class-ts'] = 'Hide';
                _setRegionExpanded(section, sid, rid, false);
            }
            d['tournaments'] = tsb.join('');
            rsb.push(_template['ms-' + section + '-region'].getText(d));
        }
        return inmore;
    }

    function _populateTournament(d, section, te, tsb, counter) {
        if (!te) return;
        var tid = te[0];
        d['t-id'] = tid;
        d['t-displayname'] = te[1];
        d['t-codename'] = $Code(te[1]);
        var cnt = (section == 'live') ? te[6] : te[5];
        counter[0] = cnt ? counter[0] + parseInt(cnt, 10) : counter[0];
        d['t-eventcount'] = cnt;
        if (d['t-eventcount']) {
            if (_isTournamentSelected(section, tid)) {
                d['class-t'] = 'Sel';
                _setSelectedTournament(section, tid);
            } else {
                d['class-t'] = null;
            }
            tsb.push(_template['ms-' + section + '-tournament'].getText(d));
        }
    }

    function _getEufaEuro(d, section) {
        var rid = $T('site').getValue('eufaeuro-rid');
        if (rid <= 0) return null;
        var re = $E('regions')[rid];
        if (!re) return null;
        d['r-id'] = rid;
        d['ee-displayname'] = d['r-displayname'] = re[1];
        d['ee-codename'] = d['r-codename'] = $Code(re[1]);
        d['ee-eventcount'] = (section == 'live') ? re[3] : re[2];
        var ssb = [];
        _populateEufaEuroSport(d, section, 1, rid, ssb);
        if (section == 'live' && ssb.length == 0) {
            return '';
        }
        if ($T('site').getValue('lang') == 'zh-cn') {
            d['lang-code'] = $T('site').getValue('lang');
        }
        if (_isEufaEuroEventExpanded(section) && ssb.length > 0) {
            _setEufaEuroEventExpanded(section, true);
        } else {
            d['class-ee'] = '';
            d['cls-tos-ee'] = 'Hide';
            _setEufaEuroEventExpanded(section, false);
        }
        return _template['ms-' + section + '-eufaeuro'].getText(d);
    }

    function _populateEufaEuroSport(d, section, sid, rid, ssb) {
        var se = $E('sports')[sid];
        if (!se) return;
        var s = _cache[sid];
        if (!s) return;
        var r = s[1][rid];
        if (!r) return;
        var its = r[2];
        d['s-id'] = sid;
        d['s-displayname'] = se[1];
        d['s-codename'] = $Code(se[1]);
        var count = (section == 'live') ? se[3] : se[2];
        if (!count) return;
        var tsb = [];
        var tc = its.length;
        for (var ti = 0; ti < tc; ++ti) {
            var te = its[ti];
            if (!te) continue;
            _populateEufaEuroTournament(d, section, te, tsb);
        }
        var srid = sid + '-' + rid;
        d['or-eventcount'] = (section == 'live') ? r[5] : r[4];
        if (d['or-eventcount']) {
            var orid = sid + '-' + rid;
            if (_isOutrightSelected(section + '-ee', sid, rid)) {
                d['class-or'] = 'Sel';
                _setSelectedOutright(section + '-ee', sid, rid);
            } else {
                d['class-or'] = null;
            }
            tsb.push(_template['ms-' + section + '-eufaeuro-outright'].getText(d));
        }
        if (tsb.length > 0) {
            if (_isSportExpanded(section + '-ee', sid)) {
                d['class-s'] = 'Sel';
                d['class-ts'] = null;
                _setSportExpanded(section + '-ee', sid, true);
            } else {
                d['class-s'] = 'Unsel';
                d['class-ts'] = 'Hide';
                _setSportExpanded(section + '-ee', sid, false);
            }
            d['tournaments'] = tsb.join('');
            ssb.push(tsb.join(''));
        }
    }

    function _populateEufaEuroTournament(d, section, te, tsb) {
        if (!te) return;
        var tid = te[0];
        d['t-id'] = tid;
        d['t-displayname'] = te[1];
        d['t-codename'] = $Code(te[1]);
        d['t-eventcount'] = (section == 'live') ? te[6] : te[5];
        if (d['t-eventcount']) {
            if (_isTournamentSelected(section + '-ee', tid)) {
                d['class-t'] = 'Sel';
                _setSelectedTournament(section + '-ee', tid);
            } else {
                d['class-t'] = null;
            }
            tsb.push(_template['ms-' + section + '-eufaeuro-tournament'].getText(d));
        }
    }

    function _getBigEvent(d, section) {
        var rid = $T('site').getValue('bigevent-rid');
        if (rid <= 0) return null;
        var re = $E('regions')[rid];
        if (!re) return null;
        d['r-id'] = rid;
        d['be-displayname'] = d['r-displayname'] = re[1];
        d['be-codename'] = d['r-codename'] = $Code(re[1]);
        d['be-eventcount'] = (section == 'live') ? re[3] : re[2];
        var ssb = [];
        var sc = _sportOrder.length;
        for (var si = 0; si < sc; ++si) {
            var sid = _sportOrder[si];
            if (sid == 11) continue;
            _populateBigEventSport(d, section, sid, rid, ssb);
        }
        if (section == 'live' && ssb.length == 0) {
            return '';
        }
        d['sports'] = ssb.join('');
        if (_isBigEventExpanded(section) && ssb.length > 0) {
            d['class-be'] = 'SptSel';
            d['class-ss'] = 'SptSel';
            _setBigEventExpanded(section, true);
        } else {
            d['class-be'] = '';
            d['class-ss'] = 'Hide';
            _setBigEventExpanded(section, false);
        }
        return _template['ms-' + section + '-bigevent'].getText(d);
    }

    function _populateBigEventSport(d, section, sid, rid, ssb) {
        var se = $E('sports')[sid];
        if (!se) return;
        var s = _cache[sid];
        if (!s) return;
        var r = s[1][rid];
        if (!r) return;
        var its = r[2];
        d['s-id'] = sid;
        d['s-displayname'] = se[1];
        d['s-codename'] = $Code(se[1]);
        var count = (section == 'live') ? se[3] : se[2];
        if (!count) return;
        var tsb = [];
        var tc = its.length;
        for (var ti = 0; ti < tc; ++ti) {
            var te = its[ti];
            if (!te) continue;
            _populateBigEventTournament(d, section, te, tsb);
        }
        var srid = sid + '-' + rid;
        d['or-eventcount'] = (section == 'live') ? r[5] : r[4];
        if (d['or-eventcount']) {
            var orid = sid + '-' + rid;
            if (_isOutrightSelected(section + '-be', sid, rid)) {
                d['class-or'] = 'Sel';
                _setSelectedOutright(section + '-be', sid, rid);
            } else {
                d['class-or'] = null;
            }
            tsb.push(_template['ms-' + section + '-bigevent-outright'].getText(d));
        }
        if (tsb.length > 0) {
            if (_isSportExpanded(section + '-be', sid)) {
                d['class-s'] = 'Sel';
                d['class-ts'] = null;
                _setSportExpanded(section + '-be', sid, true);
            } else {
                d['class-s'] = 'Unsel';
                d['class-ts'] = 'Hide';
                _setSportExpanded(section + '-be', sid, false);
            }
            d['tournaments'] = tsb.join('');
            ssb.push(_template['ms-' + section + '-bigevent-sport'].getText(d));
        }
    }

    function _populateBigEventTournament(d, section, te, tsb) {
        if (!te) return;
        var tid = te[0];
        d['t-id'] = tid;
        d['t-displayname'] = te[1];
        d['t-codename'] = $Code(te[1]);
        d['t-eventcount'] = (section == 'live') ? te[6] : te[5];
        if (d['t-eventcount']) {
            if (_isTournamentSelected(section + '-be', tid)) {
                d['class-t'] = 'Sel';
                _setSelectedTournament(section + '-be', tid);
            } else {
                d['class-t'] = null;
            }
            tsb.push(_template['ms-' + section + '-bigevent-tournament'].getText(d));
        }
    }

    function _isSportSelected(section, sid) {
        if (_state['selected-' + section + '-s'] == sid) {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if (sid == $T('od').getValue('sid') && ((section == 'all' && pid >= 10 && pid < 20) || (section == 'live' && pid >= 20 && pid < 30) || (section == 'all-be' && pid >= 40 && pid < 50) || (section == 'live-be' && pid >= 50 && pid < 60))) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _getSelectedSport(section) {
        return _state['selected-' + section + '-s'];
    }

    function _setSelectedSport(section, sid) {
        _state['selected-' + section + '-s'] = sid;
    }

    function _isSportExpanded(section, sid) {
        if (_state[section + '-s-' + sid + '-expanded']) {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if (sid == $T('od').getValue('sid') && ((section == 'all' && pid >= 10 && pid < 20) || (section == 'live' && pid >= 20 && pid < 30) || (section == 'all-be' && pid >= 40 && pid < 50) || (section == 'live-be' && pid >= 50 && pid < 60))) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _setSportExpanded(section, sid, value) {
        _state[section + '-s-' + sid + '-expanded'] = value;
    }

    function _isRegionSelected(section, sid, rid) {
        if (_state['selected-' + section + '-s'] == sid && _state['selected-' + section + '-r'] == rid) {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if (sid == $T('od').getValue('sid') && rid == $T('od').getValue('rid') && ((section == 'all' && pid >= 10 && pid < 20) || (section == 'live' && pid >= 20 && pid < 30) || (section == 'all-be' && pid >= 40 && pid < 50) || (section == 'live-be' && pid >= 50 && pid < 60))) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _getSelectedRegion(section) {
        return _state['selected-' + section + '-r'];
    }

    function _setSelectedRegion(section, sid, rid) {
        _state['selected-' + section + '-s'] = sid;
        _state['selected-' + section + '-r'] = rid;
    }

    function _isRegionExpanded(section, sid, rid) {
        if (_state[section + '-r-' + sid + '-' + rid + '-expanded']) {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if (sid == $T('od').getValue('sid') && rid == $T('od').getValue('rid') && ((section == 'all' && pid >= 10 && pid < 20) || (section == 'live' && pid >= 20 && pid < 30) || (section == 'all-be' && pid >= 40 && pid < 50) || (section == 'live-be' && pid >= 50 && pid < 60))) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _setRegionExpanded(section, sid, rid, value) {
        _state[section + '-r-' + sid + '-' + rid + '-expanded'] = value;
    }

    function _isOutrightSelected(section, sid, rid) {
        if (_state['selected-' + section + '-s'] == sid && _state['selected-' + section + '-r'] == rid && _state['selected-' + section + '-t'] == 'outright') {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if (sid == $T('od').getValue('sid') && rid == $T('od').getValue('rid') && ((section == 'all' && pid == 14) || (section == 'live' && pid == 24) || (section == 'all-be' && pid == 44) || (section == 'live-be' && pid == 54))) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _setSelectedOutright(section, sid, rid) {
        _state['selected-' + section + '-s'] = sid;
        _state['selected-' + section + '-r'] = rid;
        _state['selected-' + section + '-t'] = 'outright';
    }

    function _isTournamentSelected(section, tid) {
        if (_state['selected-' + section + '-t'] == tid) {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if (tid == $T('od').getValue('tid') && ((section == 'all' && pid >= 10 && pid < 20) || (section == 'live' && pid >= 20 && pid < 30) || (section == 'all-be' && pid >= 40 && pid < 50) || (section == 'live-be' && pid >= 50 && pid < 60))) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _getSelectedTournament(section) {
        return _state['selected-' + section + '-t'];
    }

    function _setSelectedTournament(section, tid) {
        _state['selected-' + section + '-t'] = tid;
    }

    function _isBigEventSelected(section) {
        if (_state['selected-' + section + '-be']) {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if ((section == 'all' && pid >= 40 && pid < 50) || (section == 'live' && pid >= 50 && pid < 60)) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _isEufaEuroEventExpanded(section) {
        if (_state[section + '-ee-expanded']) {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if ((section == 'all' && pid >= 60 && pid < 70) || (section == 'live' && pid >= 70 && pid < 80)) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _getSelectedEufaEuroEvent(section) {
        return _state['selected-' + section + '-ee'];
    }

    function _setSelectedEufaEuroEvent(section, sid) {
        _state['selected-' + section + '-ee'] = sid;
    }

    function _setEufaEuroEventExpanded(section, value) {
        _state[section + '-ee-expanded'] = value;
    }

    function _getSelectedBigEvent(section) {
        return _state['selected-' + section + '-be'];
    }

    function _setSelectedBigEvent(section, sid) {
        _state['selected-' + section + '-be'] = sid;
    }

    function _isBigEventExpanded(section) {
        if (_state[section + '-be-expanded']) {
            return true;
        } else if (_state['odds-drawed']) {
            return false;
        } else {
            var pid = $T('od').getValue('pid');
            if ((section == 'all' && pid >= 40 && pid < 50) || (section == 'live' && pid >= 50 && pid < 60)) {
                return true;
            } else {
                return false;
            }
        }
    }

    function _setBigEventExpanded(section, value) {
        _state[section + '-be-expanded'] = value;
    }
}
var od_OddsOptions = [null, ['h', 'a'],
    ['h', 'a'],
    ['h', 'a'],
    ['00', '01', '02', '03', '04', '10', '11', '12', '13', '14', '20', '21', '22', '23', '24', '30', '31', '32', '33', '34', '40', '41', '42', '43', '44', 'o'],
    ['1', 'x', '2'],
    ['0-1', '2-3', '4-6', '7-over'],
    ['h', 'a'],
    ['1', 'x', '2'],
    ['h', 'a'],
    ['hh', 'hd', 'ha', 'dh', 'dd', 'da', 'ah', 'ad', 'aa'],
    ['1', '2'],
    ['h', 'a'],
    ['hf', 'hl', 'af', 'al', 'ng'],
    ['00', '01', '02', '03', '10', '11', '12', '13', '20', '21', '22', '23', '30', '31', '32', '33', 'o'],
    ['x2', '12', '1x'],
    ['1', 'x', '2'],
    ['1', 'x', '2'], null
];
var od_MarketOrder = [5, 8, 16, 17, 11, 1, 7, 3, 9, 2, 12, 6, 15, 4, 14, 10, 13, 39, 99];
var od_MarketNames = {
    1: 'hdp',
    2: 'oe',
    3: 'ou',
    4: 'cs',
    5: '1x2',
    6: 'tg',
    7: 'hdp',
    8: '1x2',
    9: 'ou',
    10: 'htft',
    11: 'ml',
    12: 'oe',
    13: 'fglg',
    14: 'fhcs',
    15: 'dc',
    16: '1x2',
    17: '1x2',
    39: 'or',
    99: 'sp'
};
var od_MarketCells = {
    'hdp': ['h', 'a'],
    'oe': ['h', 'a'],
    'ou': ['h', 'a'],
    'cs': ['00', '01', '02', '03', '04', '10', '11', '12', '13', '14', '20', '21', '22', '23', '24', '30', '31', '32', '33', '34', '40', '41', '42', '43', '44', 'aos'],
    '1x2': ['1', 'x', '2'],
    'tg': ['0-1', '2-3', '4-6', '7-over'],
    'dc': ['x2', '12', '1x'],
    'htft': ['hh', 'hd', 'ha', 'dh', 'dd', 'da', 'ah', 'ad', 'aa'],
    'ml': ['1', '2'],
    'fglg': ['hf', 'hl', 'af', 'al', 'ng'],
    'fhcs': ['00', '01', '02', '03', '10', '11', '12', '13', '20', '21', '22', '23', '30', '31', '32', '33', 'aos'],
    'or': ['p'],
    'sp': ['h', 'a']
};
var _liveTimerMinuteCap = 99;

function __EuroModelOddsDisplayDrawing(sportOrder, template, data, target, syn, jerseyTemplate) {
    var _template = template;
    var _sportOrder = sportOrder;
    var _jerseyTemplate = jerseyTemplate;
    var _data = data;
    var _target = target;
    var _syn = syn;
    var _tshowtimelive = _template['div-showtime-lctv-live'];
    var _tshowtimenonlive = _template['div-showtime-lctv-nonlive'];

    function _getShowTime(text) {
        var h = parseInt(text.substring(11, 13), 10);
        if (isNaN(h)) h = 0;
        var m = parseInt(text.substring(14, 16), 10);
        if (isNaN(m)) m = 0;
        var date = new Date(parseInt(text.substring(6, 10), 10), parseInt(text.substring(0, 2), 10) - 1, parseInt(text.substring(3, 5), 10), h, m);
        if (!isNaN(date)) {
            if ($T('site').getValue('tz')) {
                var tzd = (8 * 60) + (new Date()).getTimezoneOffset();
                date = new Date(date.getTime() - tzd * 60000);
            }
            return date;
        }
        return NaN;
    }

    function _getTagEvent(eid, arr) {
        var caches = _data.caches;
        for (var cid in caches) {
            var c = caches[cid];
            if (c) {
                var tag = c.getTag(eid);
                if (tag) {
                    if (arr) {
                        arr[0] = tag;
                        arr[1] = cid;
                    }
                    return tag;
                }
            }
        }
        return null;
    }

    function _populateUrlBase(d) {
        d['url-base'] = $M('euro').getEuroUrlBase();
        d['url-hash'] = ($T('site').getValue('seo') || history.pushState) ? null : '#!/';
    }

    function _populateSport(d, sid, se) {
        if (!se) {
            se = $E('sports')[sid];
        }
        if (se) {
            d['s-id'] = se[0];
            var name = se[1];
            d['sport'] = name;
            d['s-displayname'] = name;
            d['s-codename'] = $Code(name);
            if (se[5]) {
                name = se[5];
            }
            d['s-real-displayname'] = name;
            d['s-real-codename'] = $Code(name);
        }
    }

    function _populateRegion(d, rid, re) {
        if (!re) {
            re = $E('regions')[rid];
        }
        if (re) {
            d['r-id'] = re[0];
            var name = re[1];
            d['region'] = name;
            d['r-displayname'] = name;
            d['r-codename'] = $Code(name);
        }
    }

    function _populateTournament(d, tid, te) {
        if (!te) {
            te = $E('tournaments')[tid];
        }
        if (te) {
            d['t-id'] = te[0];
            var name = te[1];
            d['tournament'] = name;
            d['league-info-cls'] = (te[10] == '') ? '' : 'LeagueInfo';
            d['tournament-info'] = te[10];
            d['t-displayname'] = name;
            d['t-codename'] = $Code(name);
        }
    }

    function _populateMarketGroup(d, mgid, mge, marketDisId) {
        if (!mge) {
            mge = $E('market-groups')[mgid];
        }
        me = $E('market-displays')[marketDisId];
        marketName = "";
        if (me) {
            marketName = me[1];
        }
        if (mge) {
            d['mg-id'] = mge[0];
            var name = mge[1];
            d['mg-codename'] = $Code(name);
            name = $Name(name);
            d['market-group'] = name + ' - ' + marketName;
            d['mg-displayname'] = name;
        }
    }

    function _populateMarketDisplay(d, mid, me) {
        if (!me) {
            me = $E('market-displays')[mid];
        }
        if (me) {
            d['m-id'] = me[0];
            var name = me[1];
            d['market'] = name;
            d['m-displayname'] = name;
            d['m-codename'] = $Code(name);
        }
    }

    function _populateMarketTab(d, mtid, mte) {
        if (!mte) {
            mte = $E('market-tabs')[mtid];
        }
        if (mte) {
            d['mt-id'] = mte[0];
            var name = mte[1];
            d['mt-displayname'] = name;
            d['mt-codename'] = $Code(name);
        }
    }

    function _populateDateTab(d, dtid, dte) {
        if (!dte) {
            dte = $E('date-tabs')[dtid];
        }
        if (dte) {
            d['dt-id'] = dte[0];
            var name = dte[1];
            d['dt-displayname'] = name;
            d['dt-codename'] = $Code(name);
        }
    }

    function _populateRefresh(d) {
        var dr = {};
        dr['count'] = _syn.refreshCount;
        dr['re-no'] = _target.refreshCount++;
        dr['refresh-text'] = (_syn.cooldownCount ? _template['refresh-text-wait'] : _template['refresh-text']).getText(dr);
        d['refresh-button'] = _template['refresh-button'].getText(dr);
    }

    function _getTwoDigits(n) {
        if (n < 10) {
            return '0' + n;
        } else {
            return n;
        }
    }

    function _getCacheDate() {
        var cd = $T('od').getValue('cd');
        return new Date(parseInt(cd.substring(0, 4), 10), parseInt(cd.substring(4, 6), 10) - 1, parseInt(cd.substring(6, 8), 10));
    }

    function _getDateTabUrl(sdt) {
        if (sdt == 1) {
            return '';
        } else if (sdt == 8) {
            return $Code($E('date-tabs')[8][1]);
        } else {
            var today = _getCacheDate();
            var time = 24 * 60 * 60 * 1000;
            var date = new Date(today.getTime() + (sdt - 1) * time);
            return date.getFullYear() + '-' + _getTwoDigits(date.getMonth() + 1) + '-' + _getTwoDigits(date.getDate());
        }
    }

    function _populateEvent(d, eid, e) {
        if (!e) {
            var t = _getTagEvent(eid);
            if (t) {
                e = t[2];
            }
        }
        if (e) {
            d['e-id'] = e[0];
            var name = e[1];
            var escName = $Name(name);
            d['home'] = escName;
            d['h-displayname'] = escName;
            d['h-codename'] = $Code(name);
            name = e[2];
            escName = $Name(name);
            d['away'] = escName;
            d['a-displayname'] = escName;
            d['a-codename'] = $Code(name);
        }
    }

    function _populateHome(d) {
        var p = $E('pages')[2];
        if (p) {
            var name = p[1];
            d['homepage'] = name;
            d['ho-displayname'] = name;
            d['ho-codename'] = $Code(name);
        }
    }

    function _populateLiveBetting(d) {
        var p = $E('pages')[20];
        if (p) {
            var name = p[1];
            d['livebetting'] = name;
            d['lb-displayname'] = name;
            d['lb-codename'] = $Code(name);
        }
    }

    function _populateMixParlay(d) {
        p = $E('pages')[30];
        if (p) {
            var name = p[1];
            d['mixparlay'] = name;
            d['mp-displayname'] = name;
            d['mp-codename'] = $Code(name);
        }
    }

    function _populateEufaEuroEvent(d) {
        var rid = $T('site').getValue('eufaeuro-rid');
        if (rid) {
            var re = $E('regions')[rid];
            if (re) {
                var name = re[1];
                d['eufaeuroevent'] = name;
                d['ee-displayname'] = name;
                d['ee-codename'] = $Code(name);
            }
        }
    }

    function _populateBigEvent(d) {
        var rid = $T('site').getValue('bigevent-rid');
        if (rid) {
            var re = $E('regions')[rid];
            if (re) {
                var name = re[1];
                d['bigevent'] = name;
                d['be-displayname'] = name;
                d['be-codename'] = $Code(name);
            }
        }
    }

    function _populateOutright(d) {
        var p = $E('pages')[14];
        if (p) {
            var name = p[1];
            d['outright'] = name;
            d['or-displayname'] = name;
            d['or-codename'] = $Code(name);
        }
    }

    function _populateDate(d, date) {
        var da = {};
        da['month'] = $E('months')[date.getMonth() + 1][1];
        da['day'] = $E('days')[date.getDate()][1];
        d['date'] = _template['date'].getText(da);
    }

    function _populateLiveTime(d, tag, marketGroupId) {
        var e = tag[2];
        var x = tag[3];
        var hScore = e[7];
        var aScore = e[8];
        if (marketGroupId > 0) {
            if (x) {
                x = x[6][marketGroupId];
            }
            if (e[11][marketGroupId]) {
                hScore = e[11][marketGroupId][0];
                aScore = e[11][marketGroupId][1];
            } else {
                hScore = 0;
                aScore = 0;
            }
        }
        d['date'] = hScore + '-' + aScore;
        d['score-h'] = hScore;
        d['score-a'] = aScore;
        live = $E('sections')[1][1];
        if (x && x[1]) {
            var p = x[1];
            d['period'] = p;
            d['period-current'] = 0;
            d['timer-current'] = 0;
            d['period-total'] = x[3];
            var injuryTime = parseInt('' + x[9], 10);
            if (p) {
                var now = new Date();
                var start = tag[6];
                var m = parseInt((now - start) / 60000 + x[2]);
                if (m > _liveTimerMinuteCap) {
                    m = _liveTimerMinuteCap;
                }
                d['period-current'] = m;
                var nt = [];
                var lt = [];
                nt.push('<font color="red">');
                if (tag[0][0] == 1) {
                    switch (p) {
                    case 1:
                        nt.push('1H ');
                        nt.push(m);
                        nt.push('\'');
                        lt.push('1H ');
                        lt.push(m);
                        lt.push('\'');
                        d['timer-current'] = m;
                        break;
                    case 2:
                        nt.push('2H ');
                        nt.push(m);
                        nt.push('\'');
                        lt.push('2H ');
                        lt.push(m);
                        lt.push('\'');
                        d['timer-current'] = m + 45;
                        break;
                    case 3:
                        nt.push('1E ');
                        nt.push(m);
                        nt.push('\'');
                        lt.push('1E ');
                        lt.push(m);
                        lt.push('\'');
                        d['timer-current'] = m + 90;
                        break;
                    case 4:
                        nt.push('2E ');
                        nt.push(m);
                        nt.push('\'');
                        lt.push('2E ');
                        lt.push(m);
                        lt.push('\'');
                        d['timer-current'] = m + 105;
                        break;
                    case 5:
                        nt.push(x[7]);
                        lt.push(x[7]);
                        d['timer-current'] = 45;
                        break;
                    default:
                        nt.push(live);
                        lt.push(live);
                        break;
                    }
                } else {
                    switch (p) {
                    case 5:
                        nt.push(x[7]);
                        lt.push(x[7]);
                        d['timer-current'] = 45;
                        break;
                    default:
                        nt.push(live);
                        lt.push(live);
                        break;
                    }
                }
                nt.push('</font>');
                if (injuryTime && injuryTime > 0) {
                    d['injuryTime'] = injuryTime;
                    d['live-time-only'] = nt.join('');
                    d['time'] = _template['odds-display-live-injury-time'].getText(d);
                    d['lc-time'] = lt.join('') + _template['lc-live-injury-time'].getText(d);
                } else {
                    d['time'] = nt.join('');
                    d['lc-time'] = lt.join('');
                }
            } else {
                d['time'] = '<font color="red"><i>' + live + '</i></font>';
                d['lc-time'] = live;
            }
        } else {
            d['time'] = '<font color="red"><i>' + live + '</i></font>';
            d['lc-time'] = live;
            d['period'] = 0;
            d['period-current'] = 0;
            d['period-total'] = 0;
        }
    }

    function _populateRedCards(d, tag, marketGroupId) {
        var e = tag[2];
        var x = tag[3];
        var sid = tag[0][0];
        if (marketGroupId > 0) {
            if (x) {
                x = x[6][marketGroupId];
            }
        }
        if (x && sid == 1) {
            var hrc = x[4];
            var arc = x[5];
            if (hrc) {
                d['rcc-h'] = 'RC' + hrc;
                d['rcs-h'] = '<span class="RC" title="' + _template.rc.getText() + '">&nbsp;</span>';
                var rcs = [];
                for (var i = 0; i < hrc; ++i) {
                    rcs.push('<span class="RedCard">&nbsp;</span>');
                }
                d['rc-h'] = rcs.join('');
            } else {
                d['rc-h'] = '';
                d['rcc-h'] = '';
                d['rcs-h'] = '';
            }
            if (arc) {
                d['rcc-a'] = 'RC' + arc;
                d['rcs-a'] = '<span class="RC" title="' + _template.rc.getText() + '">&nbsp;</span>';
                var rcs = [];
                for (var i = 0; i < arc; ++i) {
                    rcs.push('<span class="RedCard">&nbsp;</span>');
                }
                d['rc-a'] = rcs.join('');
            } else {
                d['rc-a'] = '';
                d['rcc-a'] = '';
                d['rcs-a'] = '';
            }
        } else {
            d['rc-h'] = '';
            d['rcc-h'] = '';
            d['rcs-h'] = '';
            d['rc-a'] = '';
            d['rcc-a'] = '';
            d['rcs-a'] = '';
        }
    }

    function _getHandicap(tag) {
        var hdp = 0;
        if (!tag) return hdp;
        if (tag[5] !== undefined) return tag[5];
        var oset = tag[4];
        if (!oset || !oset[2]) return hdp;
        var os = oset[2][1];
        if (os) {
            var maxbet = 0;
            var c = os.length;
            for (var i = 0; i < c; ++i) {
                var o = os[i];
                if (!o) continue;
                var ob = o[1];
                if (!ob) continue;
                if (maxbet <= ob[2]) {
                    if (ob[3] > 0) {
                        maxbet = ob[2];
                        hdp = 1;
                    } else if (ob[3] < 0) {
                        maxbet = ob[2];
                        hdp = 2;
                    }
                }
            }
        }
        if (hdp) return hdp;
        os = oset[2][7];
        if (os) {
            maxbet = 0;
            c = os.length;
            for (i = 0; i < c; ++i) {
                o = os[i];
                if (!o) continue;
                ob = o[1];
                if (!ob) continue;
                if (maxbet <= ob[2]) {
                    if (ob[3] > 0) {
                        maxbet = ob[2];
                        hdp = 1;
                    } else if (ob[3] < 0) {
                        maxbet = ob[2];
                        hdp = 2;
                    }
                }
            }
        }
        return hdp;
    }

    function _getContentPoints(mid, p) {
        switch (mid) {
        case 1:
        case 7:
            if (p != null && p != undefined) {
                var f = parseFloat(p);
                var hs;
                var as;
                if (f > 0) {
                    hs = '-';
                    as = '+';
                } else if (f < 0) {
                    hs = '+';
                    as = '-';
                } else {
                    hs = '';
                    as = '';
                }
                if (f < 0) f = -f;
                var n = parseInt(f);
                var d = parseInt(f * 100) % 100;
                if (d < 25) {
                    return [hs + n + '.00', as + n + '.00'];
                } else if (d == 50) {
                    return [hs + n + '.50', as + n + '.50'];
                }
                return [hs + f, as + f];
            }
            break;
        case 3:
        case 9:
            if (p != null && p != undefined) {
                f = parseFloat(p);
                if (f < 0) f = -f;
                var n = parseInt(f);
                var d = parseInt(f * 100) % 100;
                if (d < 25) {
                    return [n + '.00', n + '.00'];
                } else if (d == 50) {
                    return [n + '.50', n + '.50'];
                }
                return [p, p];
            }
            break;
        }
        return null;
    }

    function _populateTeamName(d, marketGroupId) {
        var homeName = d['h-displayname'];
        var awayName = d['a-displayname'];
        d['home'] = homeName;
        d['away'] = awayName;
        if (marketGroupId != 0) {
            var marketGroup = $E('market-groups')[marketGroupId];
            if (marketGroup) {
                var home = marketGroup[2];
                var away = marketGroup[3];
                if (home != '') {
                    home = home.replace('_{homeext}_', $Name(marketGroup[4]));
                    home = home.replace('_{awayext}_', $Name(marketGroup[5]));
                    home = home.replace('_{home}_', homeName);
                    home = home.replace('_{away}_', awayName);
                    home = home.replace('{home}', homeName);
                    home = home.replace('{away}', awayName);
                    d['home'] = home;
                }
                if (away != '') {
                    away = away.replace('_{homeext}_', $Name(marketGroup[4]));
                    away = away.replace('_{awayext}_', $Name(marketGroup[5]));
                    away = away.replace('_{home}_', homeName);
                    away = away.replace('_{away}_', awayName);
                    away = away.replace('{home}', homeName);
                    away = away.replace('{away}', awayName);
                    d['away'] = away;
                }
            }
        }
    }

    function _populateTagEvent(tag, subevent, live, pais, tprefix, livecenter, ms) {
        var pid = $T('od').getValue('pid');
        var tid = tag[1][0];
        var e = tag[2];
        var eid = e[0];
        var oset = tag[4];
        var odm = oset[2];
        if (!odm) return;
        var tshowtime = (live) ? _tshowtimelive : _tshowtimenonlive;
        var d = {};
        _populateUrlBase(d);
        _populateLiveBetting(d);
        _populateMixParlay(d);
        _populateBigEvent(d);
        _populateSport(d, 0, tag[0]);
        _populateTournament(d, 0, tag[1]);
        _populateEvent(d, 0, tag[2]);
        var m = $M('fa');
        if (m && m.isFavouriteSelected && m.isFavouriteSelected('ev', eid)) {
            d['class-afa'] = 'Hide';
            d['class-rfa'] = null;
        } else {
            d['class-afa'] = null;
            d['class-rfa'] = 'Hide';
        }
        d['favourite'] = _template['div-favourite-e'].getText(d);
        if (live) {
            _populateLiveTime(d, tag, 0);
            _populateRedCards(d, tag, 0);
        } else {
            var date = _getShowTime(e[5]);
            if (!isNaN(date)) {
                _populateDate(d, date);
                if (e[4] & 0x1) {
                    d['time'] = '**:**';
                } else {
                    d['time'] = _getTwoDigits(date.getHours()) + ':' + _getTwoDigits(date.getMinutes());
                }
            }
            if ((e[4] & 0x04) || (e[4] & 0x08)) {
                d['icon-live'] = _template['icon-live'].getText();
            }
        }
        if (subevent) {
            var n = (live && eid != $T('od').getValue('eid')) ? 'e-sub-live' : 'e-sub';
            d['e-sub-2'] = _template[n + '-2'].getText(d);
            d['e-sub-4'] = _template[n + '-4'].getText(d);
        }
        var tv = $E('videos')[eid];
        var lv = $E('livevideos')[eid];
        var rb = $E('running')[eid];
        if (livecenter !== undefined) {
            if ((lv || rb) && !livecenter) return;
            if (!(lv || rb) && livecenter) return;
        }
        if (lv || rb || tv) {
            if (lv || rb) {
                d['lc-s'] = _template['a-lc-s'].getText(d);
                d['lc-l'] = _template['a-lc-l'].getText(d);
            }
            if (tv) {
                d['tv-s'] = _template['a-tv-s'].getText(d);
                d['tv-l'] = _template['a-tv-l'].getText(d);
            }
        } else {
            d['showtime'] = _template['div-showtime'].getText(d);
        }
        d['class-statistics'] = e[9] ? 'IconStats' : 'IconStatsGray';
        d['tt_statistics'] = e[9] ? _template.stat.getText() : _template.no_stat.getText();
        d['o-total'] = oset[0][1];
        _populateMarketTab(d, 4);
        if (pid >= 70) {
            _populateLiveBetting(d);
            _populateEufaEuroEvent(d);
            d['type-id'] = 's';
            d['icons'] = _template['live-ee-icons'].getText(d);
        } else if (pid >= 60) {
            _populateEufaEuroEvent(d);
            d['type-id'] = 's';
            d['icons'] = _template['all-ee-icons'].getText(d);
        } else if (pid >= 50) {
            _populateLiveBetting(d);
            _populateBigEvent(d);
            d['type-id'] = 's';
            d['icons'] = _template['live-be-icons'].getText(d);
        } else if (pid >= 40) {
            _populateBigEvent(d);
            d['type-id'] = 's';
            d['icons'] = _template['all-be-icons'].getText(d);
        } else if (pid >= 30) {
            _populateMixParlay(d);
            d['type-id'] = 'm';
            d['icons'] = _template['mp-icons'].getText(d);
        } else {
            d['type-id'] = 's';
            if (pid >= 20) {
                d['icons'] = _template['live-icons'].getText(d);
            } else {
                d['icons'] = _template['all-icons'].getText(d);
            }
        }
        var fmids = {};
        var tidprice = _template['id-price'];
        var threfprice = _template['href-price'];
        if (oset[0][0] > 0) {
            for (var marketDisplayId in odm) {
                marketDisplayId = parseInt(marketDisplayId);
                var os = odm[marketDisplayId];
                if (!os) continue;
                var mop = od_OddsOptions[marketDisplayId];
                if (!mop) continue;
                var mtn = od_MarketNames[marketDisplayId];
                var isLiveCS = (live && (marketDisplayId == 4 || marketDisplayId == 14));
                if (!mtn) continue;
                var rt = isLiveCS ? _template[tprefix + '-tr-cs-live'] : _template[tprefix + '-tr-' + mtn];
                if (!rt) continue;
                var cns = od_MarketCells[mtn];
                if (!cns) continue;
                d['m-id'] = marketDisplayId;
                var oc = os.length;
                for (var oi = 0; oi < oc; ++oi) {
                    var o = os[oi];
                    if (!o) continue;
                    d['o-id'] = o[0];
                    var marketGroupId = o[1][1];
                    if (marketGroupId > 0) {
                        if (live) {
                            _populateLiveTime(d, tag, marketGroupId);
                            _populateRedCards(d, tag, marketGroupId);
                            tshowtime = _template['sp-div-showtime-lctv-live'];
                        } else {
                            tshowtime = _template['sp-div-showtime-lctv-nonlive'];
                        }
                        d['favourite'] = _template['div-favourite-e'].getText(d);
                    }
                    if (rb || lv || tv || marketGroupId > 0) {
                        if (tv || lv) {
                            d["tv-nonlive"] = _template['a-tv-nonlive'].getText(d);
                        }
                        if (rb) {
                            d["lc-nonlive"] = _template['a-lc-nonlive'].getText(d);
                        }
                        d['showtime'] = tshowtime.getText(d);
                    }
                    var cnc = cns.length;
                    var ps = _getContentPoints(marketDisplayId, o[1][5]);
                    var ops = o[2];
                    var sbCsOddsHome = [];
                    var sbCsOddsDraw = [];
                    var sbCsOddsAway = [];
                    for (var cni = 0; cni < cnc; ++cni) {
                        var cn = cns[cni];
                        if (marketDisplayId == 6) {
                            d['tg-' + cn + '-class'] = '';
                            if (!ops[cni]) {
                                d['id-price-' + cn] = '';
                                d['href-price-' + cn] = '#';
                                d['tg-' + cn + '-class'] = 'OddsDisabled';
                                continue;
                            }
                        }
                        d[cn] = d['price'] = tilib_GetPriceString(ops[cni]);
                        if (ps) {
                            d[cn + '-p'] = ps[cni];
                        }
                        d['option'] = mop[cni];
                        d['id-price-' + cn] = tidprice.getText(d);
                        d['href-price-' + cn] = threfprice.getText(d);
                        var pai = (pais) ? pais[o[0] + '-' + cni] : 0;
                        var paic = pai ? ((pai < 0) ? 'PriceDown' : 'PriceUp') : '';
                        if ($M('bs').isOptionSelected(d['type-id'], d['o-id'], d['option'])) {
                            paic += ' OddsSel';
                        }
                        d['pai-' + cn] = paic;
                        var csSuffixInfo = {
                            s: '',
                            had: 0
                        };
                        _getCorrectScoreSuffix(null, cn, csSuffixInfo);
                        d['suffix-' + cn] = csSuffixInfo.s;
                        if (isLiveCS) {
                            if (ops[cni] == undefined || ops[cni] <= 1) {
                                if (cn == 'aos') {
                                    d['pai-' + cn] = 'Hide';
                                }
                                continue;
                            } else if (cn == 'aos') {
                                continue;
                            } else {
                                var dcs = {};
                                var csOddsTmpl = _template['a-link-cs-odds'];
                                _getCorrectScoreSuffix(e, cn, csSuffixInfo);
                                dcs['suffix-cs'] = csSuffixInfo.s;
                                dcs['id-price-cs'] = d['id-price-' + cn];
                                dcs['href-price-cs'] = d['href-price-' + cn];
                                dcs['pai-cs'] = d['pai-' + cn];
                                dcs['price-cs'] = d['price'];
                                csOddsTmpl = csOddsTmpl.getText(dcs);
                                switch (csSuffixInfo.had) {
                                case 1:
                                    sbCsOddsHome.push(csOddsTmpl);
                                    break;
                                case 2:
                                    sbCsOddsAway.push(csOddsTmpl);
                                    break;
                                case 0:
                                default:
                                    sbCsOddsDraw.push(csOddsTmpl);
                                    break;
                                }
                            }
                        }
                    }
                    if (isLiveCS) {
                        d['cs-live-odds-home'] = sbCsOddsHome.join('');
                        d['cs-live-odds-draw'] = sbCsOddsDraw.join('');
                        d['cs-live-odds-away'] = sbCsOddsAway.join('');
                    }
                    var marketId = o[1][0];
                    if (fmids[marketGroupId]) {
                        fmids[marketGroupId][marketDisplayId] = 1;
                    } else {
                        fmids[marketGroupId] = {
                            marketDisplayId: 1
                        };
                    }
                    _populateTeamName(d, marketGroupId);
                    var marketDisplayGroup = marketDisplayId;
                    if (marketId >= 99) {
                        rt = _template['st-tr-' + mtn];
                        marketDisplayGroup = 99;
                    }
                    switch (marketId) {
                    case 16:
                        d['asian1x2home'] = _template['ft-asian1x2-home-tt'].getText();
                        d['asian1x2draw'] = _template['ft-asian1x2-draw-tt'].getText();
                        d['asian1x2away'] = _template['ft-asian1x2-away-tt'].getText();
                        break;
                    case 17:
                        d['asian1x2home'] = _template['fh-asian1x2-home-tt'].getText();
                        d['asian1x2draw'] = _template['fh-asian1x2-draw-tt'].getText();
                        d['asian1x2away'] = _template['fh-asian1x2-away-tt'].getText();
                        break;
                    default:
                        d['asian1x2home'] = d['home'];
                        d['asian1x2draw'] = '';
                        d['asian1x2away'] = d['away'];
                        break;
                    }
                    m = ms[marketDisplayGroup];
                    if (!m) {
                        ms[marketDisplayGroup] = m = {
                            tournaments: [
                                [tid, []]
                            ],
                            marketGroups: {},
                            all: []
                        };
                    }
                    var text = rt.getText(d);
                    m.all.push(text);
                    var t = m.tournaments[m.tournaments.length - 1];
                    if (t[0] != tid) {
                        t = [tid, []];
                        m.tournaments.push(t);
                    }
                    t[1].push(text);
                    var mg = m.marketGroups[marketGroupId];
                    if (!mg) {
                        m.marketGroups[marketGroupId] = {};
                        m.marketGroups[marketGroupId][marketDisplayId] = mg = [];
                    } else {
                        mg = m.marketGroups[marketGroupId][marketDisplayId];
                        if (!mg) {
                            m.marketGroups[marketGroupId][marketDisplayId] = mg = [];
                        }
                    }
                    mg.push(text);
                }
            }
        }
        var sid = $T('od').getValue('sid');
        var dm = oset[0][2];
        if (!dm) return;
        var c = dm.length;
        for (var i = 0; i < c; ++i) {
            marketId = dm[i][0];
            marketGroupId = dm[i][1];
            marketDisplayId = dm[i][2];
            if (fmids[marketGroupId] && fmids[marketGroupId][marketDisplayId]) continue;
            mtn = od_MarketNames[marketDisplayId];
            if (!mtn) continue;
            rt = _template[tprefix + '-tr-' + mtn + '-0'];
            if (!rt) continue;
            d['m-id'] = marketDisplayId;
            d['o-id'] = 'd-' + eid + '-' + marketId;
            if (rb || tv) {
                d['showtime'] = tshowtime.getText(d);
            }
            oriMarketDisplayId = marketDisplayId;
            if (marketGroupId > 0) {
                if (live) {
                    _populateLiveTime(d, tag, marketGroupId);
                    _populateRedCards(d, tag, marketGroupId);
                    tshowtime = _template['sp-div-showtime-lctv-live'];
                    d['showtime'] = tshowtime.getText(d);
                }
                rt = _template['st-tr-' + mtn + '-0'];
                marketDisplayId = 99;
            }
            m = ms[marketDisplayId];
            if (!m) {
                ms[marketDisplayId] = m = {
                    tournaments: [
                        [tid, []]
                    ],
                    marketGroups: {},
                    all: []
                };
            }
            _populateTeamName(d, marketGroupId);
            switch (marketId) {
            case 16:
                d['asian1x2home'] = _template['ft-asian1x2-home-tt'].getText();
                d['asian1x2draw'] = _template['ft-asian1x2-draw-tt'].getText();
                d['asian1x2away'] = _template['ft-asian1x2-away-tt'].getText();
                break;
            case 17:
                d['asian1x2home'] = _template['fh-asian1x2-home-tt'].getText();
                d['asian1x2draw'] = _template['fh-asian1x2-draw-tt'].getText();
                d['asian1x2away'] = _template['fh-asian1x2-away-tt'].getText();
                break;
            default:
                d['asian1x2home'] = d['home'];
                d['asian1x2draw'] = '';
                d['asian1x2away'] = d['away'];
                break;
            }
            text = rt.getText(d);
            m.all.push(text);
            t = m.tournaments[m.tournaments.length - 1];
            if (t[0] != tid) {
                t = [tid, []];
                m.tournaments.push(t);
            }
            t[1].push(text);
            mg = m.marketGroups[marketGroupId];
            if (!mg) {
                m.marketGroups[marketGroupId] = {};
                m.marketGroups[marketGroupId][oriMarketDisplayId] = mg = [];
            } else {
                mg = m.marketGroups[marketGroupId][oriMarketDisplayId];
                if (!mg) {
                    m.marketGroups[marketGroupId][oriMarketDisplayId] = mg = [];
                }
            }
            mg.push(text);
        }
    }

    function _getCorrectScoreSuffix(eventTag, suffix, csSuffixInfo) {
        var hScore = (eventTag == undefined || eventTag[7] == undefined) ? 0 : eventTag[7];
        var aScore = (eventTag == undefined || eventTag[8] == undefined) ? 0 : eventTag[8];
        var hSuffix = suffix.substring(0, 1);
        var aSuffix = suffix.substring(1);
        hSuffix = hScore + parseInt(hSuffix, 10);
        aSuffix = aScore + parseInt(aSuffix, 10);
        if (hSuffix > aSuffix) {
            csSuffixInfo.had = 1;
        } else if (aSuffix > hSuffix) {
            csSuffixInfo.had = 2;
        } else {
            csSuffixInfo.had = 0;
        }
        csSuffixInfo.s = hSuffix + ' - ' + aSuffix;
    }

    function _populateTagOutright(tag, pais, tprefix, ms, isUseColOnly) {
        var pid = $T('od').getValue('pid');
        var d = {};
        _populateUrlBase(d);
        _populateSport(d, 0, tag[0]);
        _populateTournament(d, 0, tag[1]);
        var tid = tag[1][0];
        var or = tag[2];
        d['o-id'] = or[0];
        d['opindex'] = or[1];
        d['price'] = tilib_GetPriceString(or[2]);
        d['showtime'] = or[7];
        d['team'] = or[6];
        d['m-id'] = 39;
        d['type-id'] = 'o';
        d['option'] = or[1] ? 1 : 0;
        d['id-price-or'] = _template['id-price'].getText(d);
        d['href-price-or'] = _template['href-price'].getText(d);
        var pai = (pais) ? pais[or[0]] : 0;
        var paic = pai ? ((pai < 0) ? 'PriceDown' : 'PriceUp') : '';
        if ($M('bs').isOptionSelected(d['type-id'], d['o-id'], d['option'])) {
            paic += ' OddsSel';
        }
        d['pai-or'] = paic;
        var m;
        if (pid == 13 || pid == 14 | pid == 23 || pid == 24 || pid == 43 || pid == 44 || pid == 53 || pid == 54 || pid == 64 || pid == 74) {
            m = ms[tid];
            if (!m) {
                ms[tid] = m = [];
                ms.ids.push(tid);
            }
        } else {
            m = ms[39];
            if (!m) ms[39] = m = [];
        }
        if (isUseColOnly && isUseColOnly == true) {
            m.push(_template[tprefix + '-td-' + od_MarketNames[39]].getText(d));
        } else {
            m.push(_template[tprefix + '-tr-' + od_MarketNames[39]].getText(d));
        }
    }

    function _getBreadcrumb() {
        var d = {};
        _populateUrlBase(d);
        _populateHome(d);
        var token = $P.getToken('od');
        _populateSport(d, token.getValue('sid'));
        _populateRegion(d, token.getValue('rid'));
        _populateTournament(d, token.getValue('tid'));
        _populateEvent(d, token.getValue('eid'));
        _populateLiveBetting(d);
        _populateMixParlay(d);
        _populateBigEvent(d);
        _populateEufaEuroEvent(d);
        _populateOutright(d);
        var t = _template['bc-' + token.getValue('pid')];
        if (t) {
            return t.getText(d);
        }
        return null;
    };

    function _getIconBar() {
        var e;
        var cid;
        var token = $P.getToken('od');
        var arr = [];
        var t = _getTagEvent(token.getValue('eid'), arr);
        var pid = token.getValue('pid');
        if (t) {
            e = t[2];
        }
        var d = {};
        var sb = [];
        sb.push(_getSortStyleInfo());
        sb.push(_getPriceStyleInfo());
        sb.push(_getSoundsInfo());
        sb.push(_getSBOBETVInfo(e, arr[1], pid));
        sb.push(_getTvChannelInfo(e, pid));
        if (e) {
            sb.push(_getStatisticInfo(e, pid));
            sb.push(_getForecastInfo(e, pid, token.getValue('sid')));
            sb.push(_getLiveCenterInfo(e, pid));
        }
        d['icon-bar-content'] = sb.join('');
        return _template['icon-bar'].getText(d);
    };

    function _getForecastInfo(e, pid, sid) {
        if ($T('site').getValue('asi')) {
            if (sid == 1) {
                if ((pid == 15) || (pid == 25)) {
                    var eventId = e[0];
                    if (eventId && eventId > 0) {
                        var d = {};
                        d['EventId'] = eventId;
                        d['PageId'] = pid;
                        return _template['forecast-icon'].getText(d);
                    }
                }
            }
        }
        return null;
    }

    function _getTvChannelInfo(e, pid) {
        if ($T('site').getValue('asi')) {
            var d = {};
            if (e && e[6] && e[6].length > 0 && (pid == 15 || pid == 25 || pid == 35 || pid == 45 || pid == 55)) {
                d['channel'] = e[6];
            } else {
                d['channel'] = _template['msg-tvchannel'].getText();
            }
            d['tv-class'] = 'IconBTVCOn';
            d['IsNewTV'] = $T('site').getValue('isNewTV');
            return _template['tv-channel-icon'].getText(d);
        }
        return null;
    }

    function _getSBOBETVInfo(e, cid, pid) {
        if ($T('site').getValue('asi')) {
            var eid = 0;
            var d = {};
            if (e && $E('videos')[e[0]] && (cid == 1 || cid == 8) && (pid == 15 || pid == 25 || pid == 35 || pid == 45 || pid == 55)) {
                eid = e[0];
            }
            d['eid'] = eid;
            d['onclick-function'] = _template['sbobetv-onclick'].getText(d);
            d['sbobetv-class'] = 'IconBTV';
            return _template['sbobetv-icon'].getText(d);
        }
        return null;
    }

    function _getLiveCenterInfo(e, pid) {
        if (pid == 15) {
            if (e) {
                var eid = e[0];
                var lv = $E('livevideos')[eid];
                var rb = $E('running')[eid];
                if (lv || rb) {
                    var d = {};
                    d['lc-class'] = 'IconBLC';
                    d['onclick-function'] = _template['livecenter-onclick'].getText({
                        'eid': eid
                    });
                    return _template['live-center-icon'].getText(d);
                }
            }
        }
        return null;
    }

    function _getStatisticInfo(e, pid) {
        if (pid == 15 || pid == 25 || pid == 35 || pid == 45 || pid == 55) {
            if (e) {
                var eid = e[0];
                var d = {};
                if (e[9]) {
                    d['stats-class'] = 'IconBStats';
                    d['stats-tt'] = _template.stat.getText();
                    d['onclick-function'] = _template['statistics-onclick'].getText({
                        'eid': eid
                    });
                } else {
                    d['stats-class'] = 'IconBStatsOff';
                    d['stats-tt'] = _template.no_stat.getText();
                }
                return _template['statistics-icon'].getText(d);
            }
        }
        return null;
    }

    function _getSoundsInfo() {
        var sound = $T('site').getValue('sound');
        var title = $E('sound-icon');
        if ($T('site').getValue('asi')) {
            var d = {};
            if (sound == "1") {
                d['sound-class'] = 'IconBSoundOn';
                if (title && title['off'][1]) {
                    d['sound-resx'] = title['off'][1];
                }
            } else {
                d['sound-class'] = 'IconBSoundOff';
                if (title && title['on'][1]) {
                    d['sound-resx'] = title['on'][1];
                }
            }
            return _template['sound-icon'].getText(d);
        }
        return null;
    }

    function _getSortStyleInfo() {
        var d = {};
        d['sort-id'] = $T('site').getValue('sort');
        return _template['sort-style-icon'].getText(d);
    }

    function _getPriceStyleInfo() {
        if ($T('site').getValue('asi')) {
            var psid = $T('od').getValue('ps');
            if (psid != 3) {
                var d = {};
                d['price-id'] = psid;
                return _template['price-style-icon'].getText(d);
            }
        }
        return null;
    }

    function _getSportTabs(cache) {
        var ses = $E('sports');
        var sports = cache.getSports();
        var ssid = _data.stab;
        var sb = [];
        var ttab = _template['h-sport-tab'];
        var d = {};
        d['c-id'] = cache.getId();
        var sc = _sportOrder.length;
        for (var si = 0; si < sc; ++si) {
            var sid = _sportOrder[si];
            var se = ses[sid];
            if (se && sports[sid]) {
                _populateSport(d, sid, se);
                d['sel'] = (sid == ssid) ? 'Sel' : null;
                sb.push(ttab.getText(d));
            }
        }
        d['tabs'] = sb.join('');
        return _template['h-sport-tabs'].getText(d);
    }

    function _getDateTabs() {
        var dtes = $E('date-tabs');
        var months = $E('months');
        var days = $E('days');
        var dows = $E('dows');
        var d = {};
        var tdate = _template['date'];
        var ttab;
        var token = $P.getToken('od');
        switch (token.getValue('pid')) {
        case 11:
            ttab = _template['s-date-tab'];
            break;
        case 12:
            ttab = _template['r-date-tab'];
            break;
        case 13:
            ttab = _template['t-date-tab'];
            break;
        case 14:
            ttab = _template['or-date-tab'];
            break;
        case 40:
            ttab = _template['be-date-tab'];
            break;
        case 41:
            ttab = _template['be-s-date-tab'];
            break;
        case 43:
            ttab = _template['be-t-date-tab'];
            break;
        case 44:
            ttab = _template['be-or-date-tab'];
            break;
        case 60:
            ttab = _template['ee-date-tab'];
            break;
        case 63:
            ttab = _template['ee-t-date-tab'];
            break;
        case 64:
            ttab = _template['ee-or-date-tab'];
            break;
        default:
            return null;
        }
        _populateUrlBase(d);
        _populateSport(d, token.getValue('sid'));
        _populateRegion(d, token.getValue('rid'));
        _populateTournament(d, token.getValue('tid'));
        _populateMarketTab(d, token.getValue('mt'));
        _populateBigEvent(d);
        _populateEufaEuroEvent(d);
        _populateOutright(d);
        var today = _getCacheDate();
        var sdt = $T('od').getValue('dt');
        var time = 24 * 60 * 60 * 1000;
        var dcounts = _data.dcounts;
        for (var i = 1; i <= 8; ++i) {
            var date = new Date(today.getTime() + (i - 1) * time);
            d['dt-id'] = i;
            if (i == 1) {
                d['date'] = dtes[1][1];
                d['href-date'] = null;
            } else if (i == 8) {
                d['date'] = dtes[8][1];
                d['href-date'] = $Code(dtes[8][1]);
            } else {
                d['month'] = months[date.getMonth() + 1][1];
                d['day'] = days[date.getDate()][1];
                d['date'] = dows[date.getDay()][1] + '<br/>' + tdate.getText(d);
                d['href-date'] = date.getFullYear() + '-' + _getTwoDigits(date.getMonth() + 1) + '-' + _getTwoDigits(date.getDate());
            }
            var count = dcounts[i]
            d['dt-count'] = (count) ? count : '0';
            d['class-dt'] = (i == sdt) ? 'Sel' : null;
            d['dt-' + i] = ttab.getText(d);
        }
        return _template['date-tabs'].getText(d);
    }

    function _getMarketTabs() {
        var d = {};
        var ttab;
        var token = $P.getToken('od');
        ttab = _template['market-tab-' + token.getValue('pid')];
        if (!ttab) {
            return null;
        }
        _populateUrlBase(d);
        _populateLiveBetting(d);
        _populateBigEvent(d);
        _populateEufaEuroEvent(d);
        _populateMixParlay(d);
        _populateSport(d, token.getValue('sid'));
        _populateRegion(d, token.getValue('rid'));
        _populateTournament(d, token.getValue('tid'));
        _populateEvent(d, token.getValue('eid'));
        d['href-date'] = _getDateTabUrl(token.getValue('dt'));
        var mes = $E('market-displays');
        var mcounts = _data.mcounts;
        var count = 0;
        var smt = $T('od').getValue('mt');
        var flags = $T('od').getValue('ms');
        for (var mid in mes) {
            var me = mes[mid];
            if (!me) continue;
            var flag = me[2];
            if (!flag) continue;
            if ((flags & flag) && mcounts[mid]) {
                if (mid == 99 && !data.displaySubmarket) continue;
                count += mcounts[mid];
            }
        }
        _populateMarketTab(d, 1);
        d['class-mt'] = (smt == 1) ? 'Sel' : 0;
        d['mt-count'] = count;
        d['mt-1'] = ttab.getText(d);
        count = 0;
        if (mcounts[1]) count += mcounts[1];
        if (mcounts[7]) count += mcounts[7];
        _populateMarketTab(d, 2);
        d['class-mt'] = (smt == 2) ? 'Sel' : 0;
        d['mt-count'] = count;
        d['mt-2'] = ttab.getText(d);
        count = 0;
        if (mcounts[5]) count += mcounts[5];
        if (mcounts[8]) count += mcounts[8];
        _populateMarketTab(d, 3);
        d['class-mt'] = (smt == 3) ? 'Sel' : 0;
        d['mt-count'] = count;
        d['mt-3'] = ttab.getText(d);
        count = 0;
        for (mid in mcounts) {
            if (mid == 99 && !data.displaySubmarket) continue;
            count += mcounts[mid];
        }
        _populateMarketTab(d, 4);
        d['class-mt'] = (smt == 4) ? 'Sel' : 0;
        d['mt-count'] = count;
        d['mt-4'] = ttab.getText(d);
        var tabs = _template['market-tabs'].getText(d);
        if ($T('od').getValue('mt') == 1) {
            var tmsic = _template['market-selection-item-checked'];
            var tmsiu = _template['market-selection-item-unchecked'];
            d = {};
            for (mid in mes) {
                if (mid == 99 && !data.displaySubmarket) continue;
                me = mes[mid];
                if (!me) continue;
                flag = me[2];
                if (!flag) continue;
                _populateMarketDisplay(d, mid, me);
                count = mcounts[mid];
                d['class-m'] = (count) ? '' : 'Grey';
                d['m-count'] = (count) ? count : 0;
                d['msi-' + mid] = ((flags & flag) ? tmsic : tmsiu).getText(d);
            }
            tabs = tabs + _template['market-selection'].getText(d);
        }
        return tabs;
    }

    function _getMarkets(cache, tprefix, tsuffix, refresh, livecenter) {
        var tags = cache.getTags();
        if (!tags) return null;
        var ms = {
            ids: []
        };
        var pid = $T('od').getValue('pid');
        var sid = $T('od').getValue('sid');
        var stid = (cache.getId() == 6) ? _data.stab : 0;
        var tc = tags.length;
        var sub = (tc > 1 && tprefix == 'e') ? 1 : 0
        for (var ti = 0; ti < tc; ++ti) {
            var tag = tags[ti];
            if (!tag) continue;
            if (stid && stid != tag[0][0]) continue;
            switch (cache.getType()) {
            case 'event':
                _populateTagEvent(tag, sub, (cache.getId() == 1) ? 1 : 0, cache.getPAIs(), tprefix, livecenter, ms);
                break;
            case 'outright':
                if (!livecenter) _populateTagOutright(tag, cache.getPAIs(), tprefix, ms);
                break;
            }
        }
        var flags = $T('od').getValue('ms');
        var state = $S('od');
        var tdiv;
        if (tsuffix) tdiv = _template[tprefix + '-div-market-' + tsuffix];
        if (!tdiv) tdiv = _template[tprefix + '-div-market'];
        var d = {};
        var cid = livecenter ? 8 : cache.getId();
        d['c-id'] = cid;
        var drawsTournaments = 0;
        var drawsSubmarkets = 0;
        if (pid == 2 || pid == 11 || pid == 12 || pid == 21 || pid == 22 || pid == 30 || pid == 31 || pid == 40 || pid == 41 || pid == 50 || pid == 51) {
            drawsTournaments = 1;
        } else if (pid == 15 || pid == 25 || pid == 35 || pid == 45 || pid == 55 || pid == 65 || pid == 75) {
            drawsSubmarkets = 1;
        }
        var mes = $E('market-displays');
        var mdivs = [];
        var mc = od_MarketOrder.length;
        var mfa = $M('fa');
        var ttournament = _template['div-tournament-banner'];
        var tmarketgroup = _template['div-market-group-banner'];
        for (var mi = 0; mi < mc; ++mi) {
            mid = od_MarketOrder[mi];
            var m = ms[mid];
            if (!m) continue;
            var me = mes[mid];
            if (!me) continue;
            _populateMarketDisplay(d, 0, me);
            var mtn = od_MarketNames[mid];
            var tt = _template[tprefix + '-table-' + mtn];
            if (!tt) continue;
            var mts = [];
            if (drawsTournaments) {
                var mtc = m.tournaments.length;
                var td = {};
                for (var mti = 0; mti < mtc; ++mti) {
                    var mt = m.tournaments[mti];
                    var tid = mt[0];
                    _populateTournament(td, tid);
                    if (mfa && mfa.isFavouriteSelected && mfa.isFavouriteSelected('to', tid)) {
                        td['class-afa'] = 'Hide';
                        td['class-rfa'] = null;
                    } else {
                        td['class-afa'] = null;
                        td['class-rfa'] = 'Hide';
                    }
                    mts.push(ttournament.getText(td));
                    mts.push(tt.getText({
                        'rows': mt[1].join('')
                    }));
                }
            } else if (drawsSubmarkets) {
                var mgd = {};
                var sortedMkGrp = [];
                for (var mgid in m.marketGroups) {
                    var mgp = {};
                    mgp.id = mgid;
                    mgp.data = m.marketGroups[mgid];
                    sortedMkGrp.push(mgp);
                }
                sortedMkGrp.sort(_sortMarketGroupCallback);
                for (var mIndex = 0; mIndex < sortedMkGrp.length; mIndex++) {
                    var marketGroups = sortedMkGrp[mIndex].data;
                    var smgid = sortedMkGrp[mIndex].id;
                    for (idx = 0; idx < mc; idx++) {
                        marketDispId = od_MarketOrder[idx];
                        if (!marketGroups[marketDispId]) {
                            continue;
                        }
                        var tt = _template[tprefix + '-table-' + od_MarketNames[marketDispId]];
                        var specialsClass = '';
                        if (mgid != 0) {
                            _populateMarketGroup(mgd, smgid, null, marketDispId);
                            mts.push(tmarketgroup.getText(mgd));
                            specialsClass = 'Specials';
                        }
                        var mg = marketGroups[marketDispId];
                        var text = tt.getText({
                            'rows': mg.join(''),
                            'specials-class': specialsClass
                        });
                        mts.push(text);
                    }
                }
            } else {
                mts.push(tt.getText({
                    'rows': m.all.join('')
                }));
            }
            d['table-market'] = mts.join('');
            var id = 'od-ma-' + cid + '-' + mid;
            if ((pid == 11 || pid == 21 || pid == 31) && sid == 1) {
                id += '-s-1';
                if (!state[id]) {
                    if (mid == 5 || mid == 8 || mid == 3 || mid == 9) {
                        state[id] = 'Open';
                    } else {
                        state[id] = 'Closed';
                    }
                }
            }
            d['class-m'] = (state[id] == 'Closed') ? 'Closed' : 'Open';
            var flag = me[2];
            d['class-am'] = (flag && (flags & flag)) ? 'Hide' : null;
            d['class-rm'] = (flag && (flags & flag)) ? null : 'Hide';
            if (refresh) {
                _populateRefresh(d);
            }
            mdivs.push(tdiv.getText(d));
        }
        return mdivs.join('');
    };

    function _sortMarketGroupCallback(mkGrp1, mkGrp2) {
        var mg1 = $E('market-groups')[mkGrp1.id];
        var mg2 = $E('market-groups')[mkGrp2.id];
        if (mg1 && mg2) {
            if (mg1[7] != mg2[7]) {
                return (mg1[7] < mg2[7]) ? -1 : 1;
            }
        }
    }

    function _getOutrightMarkets(cache) {
        var tags = cache.getTags();
        if (!tags) return null;
        var ts = {
            ids: []
        };
        var tc = tags.length;
        var lowestOddsDate = {};
        var isUseColOnly = true;
        for (var ti = 0; ti < tc; ++ti) {
            var tag = tags[ti];
            if (!tag) continue;
            var tid = tag[1][0];
            if (!lowestOddsDate[tid]) {
                lowestOddsDate[tid] = tag[2][7];
            }
            _populateTagOutright(tag, cache.getPAIs(), 't', ts, isUseColOnly);
        }
        var state = $S('od');
        var tdiv = _template['r-div-or'];
        var d = {};
        var cid = cache.getId();
        d['c-id'] = cid;
        var tes = $E('tournaments');
        var tdivs = [];
        var tc = ts.ids.length;
        for (var ti = 0; ti < tc; ++ti) {
            var tid = ts.ids[ti];
            var t = ts[tid];
            t = _sortORData(t);
            if (!t) continue;
            var te = tes[tid];
            if (!te) continue;
            _populateTournament(d, 0, te);
            var tt = _template['t-table-or'];
            if (!tt) continue;
            d['table-market'] = tt.getText({
                'rows': t.join('')
            });
            d['class-or'] = (state['od-or-' + cid + '-' + tid] == 'Closed') ? 'Closed' : 'Open';
            d['lowestOddsDate'] = lowestOddsDate[tid];
            tdivs.push(tdiv.getText(d));
        }
        return tdivs.join('');
    };

    function _sortORData(t) {
        var sb = [];
        var totRow = Math.floor(t.length / 2) + (t.length % 2);
        var d = {};
        for (var i = 0; i < totRow; i++) {
            if ((totRow + i) < t.length) {
                d['row'] = _populateLeftRightInd(t[i], 'L') + _populateLeftRightInd(t[totRow + i], 'R');
            } else {
                d['row'] = _populateLeftRightInd(t[i], 'L') + '<td class="OddsTabSpan"></td>';
            }
            sb.push(_template['t-row-or'].getText(d));
        }
        return sb;
    }

    function _populateLeftRightInd(str, val) {
        if (str.indexOf('[ind-L-R]') > 0) {
            str = str.replace('[ind-L-R]', val);
        }
        return str;
    }

    function _getHome() {
        var thome = _template['div-home'];
        var d = {};
        var sb = [];
        var cache = _data.caches[6];
        if (cache) {
            var ms = _getMarkets(cache, 's', 'nonlive', true);
            d['section'] = $E('sections')[6][1];
            d['class-section'] = 'Nonlive';
            d['sport-tabs'] = _getSportTabs(cache);
            d['markets'] = ms;
            sb.push(thome.getText(d));
        }
        cache = _data.caches[7];
        if (cache) {
            ms = _getMarkets(cache, 's', 'nonlive', true);
            if (ms && ms.length > 0) {
                d['section'] = $E('sections')[7][1];
                d['class-section'] = 'Nonlive';
                d['sport-tabs'] = null;
                d['markets'] = ms;
                sb.push(thome.getText(d));
            }
        }
        return (sb.length > 0) ? sb.join('') : _template['msg-noevent'].getText();
    };

    function _getMixParlay() {
        var ses = $E('sports');
        var dtes = $E('date-tabs');
        var tsport = _template['mp-sport'];
        var tdate = _template['mp-date'];
        var sb = [];
        d = {};
        _populateUrlBase(d);
        _populateMixParlay(d);
        _populateRefresh(d);
        d['market-tabs'] = _getMarketTabs();
        var ssb = [];
        var ssid = $T('od').getValue('sid');
        var sc = _sportOrder.length;
        for (var si = 0; si < sc; ++si) {
            var sid = _sportOrder[si];
            var se = ses[sid];
            if (!se || (sid != ssid && !se[4])) continue;
            _populateSport(d, sid, se);
            d['class-s'] = (sid == ssid) ? 'Sel' : null;
            ssb.push(tsport.getText(d));
        }
        d['sports'] = ssb.join('');
        _populateSport(d, ssid);
        var today = _getCacheDate();
        var sdt = $T('od').getValue('dt');
        var time = 24 * 60 * 60 * 1000;
        for (var i = 1; i <= 9; ++i) {
            var date = new Date(today.getTime() + (i - 1) * time);
            var month = date.getMonth() + 1;
            var day = date.getDate();
            d['dt-id'] = i;
            if (i == 9) {
                d['date'] = dtes[9][1];
                d['href-date'] = $Code(dtes[9][1]);
            } else if (i == 8) {
                d['date'] = dtes[8][1];
                d['href-date'] = $Code(dtes[8][1]);
            } else {
                d['date'] = month + '/' + day;
                if (i == 1 || i == 2) {
                    d['date'] += ' [' + dtes[i][1] + ']';
                }
                if (i == 1) {
                    d['href-date'] = null;
                } else {
                    d['href-date'] = date.getFullYear() + '-' + _getTwoDigits(month) + '-' + _getTwoDigits(day);
                }
            }
            d['class-dt'] = (i == sdt) ? 'Sel' : null;
            d['dt-' + i] = tdate.getText(d);
        }
        var markets = null;
        var cache = _data.caches[3];
        if (cache) {
            markets = _getMarkets(cache, 't', 'nonlive');
        }
        d['MaxPayout'] = _mpMaxPayout;
        d['HalftPayout'] = _mpHalftPayout;
        d['section'] = $E('sections')[3][1];
        d['markets'] = (markets && markets.length > 0) ? markets : _template['msg-noevent'].getText();
        return _template['div-mixparlay'].getText(d);
    }

    function _getSport() {
        var pid = $T('od').getValue('pid');
        var tsport = _template['div-sport'];
        var d = {};
        var sb = [];
        if (pid == 21) {
            var cache = _data.caches[1];
            if (cache) {
                var ms = _getMarkets(cache, 's', 'live', false, true);
                if (ms && ms.length > 0) {
                    d['section'] = $E('sections')[8][1];
                    d['class-section'] = 'Live';
                    d['markets'] = '<div class="LiveMarket">' + ms + '</div>';
                    _populateRefresh(d);
                    sb.push(tsport.getText(d));
                }
                ms = _getMarkets(cache, 's', 'live', false, false);
                if (ms && ms.length > 0) {
                    d['section'] = $E('sections')[1][1];
                    d['class-section'] = 'Live';
                    d['markets'] = '<div class="LiveMarket">' + ms + '</div>';
                    _populateRefresh(d);
                    sb.push(tsport.getText(d));
                }
            }
            var cache = _data.caches[4];
            if (cache) {
                ms = _getOutrightMarkets(cache);
                if (ms && ms.length > 0) {
                    d['section'] = $E('market-displays')[39][1];
                    d['class-section'] = 'Live';
                    d['markets'] = '<div class="LiveMarket">' + ms + '</div>';
                    _populateRefresh(d);
                    sb.push(tsport.getText(d));
                }
            }
            return (sb.length > 0) ? sb.join('') : _template['msg-noevent'].getText();
        } else {
            d['date-tabs'] = _getDateTabs();
            d['section'] = $E('sports')[$T('od').getValue('sid')][1];
            d['class-section'] = 'NonLive';
            _populateRefresh(d);
            cache = _data.caches[1];
            if (cache) {
                var ms = _getMarkets(cache, 's', 'live');
                if (ms && ms.length > 0) {
                    sb.push('<div class="LiveMarket">');
                    sb.push(ms);
                    sb.push('</div>');
                }
            }
            cache = _data.caches[2];
            if (cache) {
                ms = _getMarkets(cache, 's', 'nonlive');
                if (ms && ms.length > 0) {
                    sb.push('<div class="NonLiveMarket">');
                    sb.push(ms);
                    sb.push('</div>');
                }
            }
            d['markets'] = (sb.length > 0) ? sb.join('') : _template['msg-noevent'].getText();
            return tsport.getText(d);
        }
    }

    function _getRegion() {
        var pid = $T('od').getValue('pid');
        var re = $E('regions')[$T('od').getValue('rid')];
        if (!re) return null;
        var d = {};
        _populateRegion(d, 0, re);
        _populateSport(d, $T('od').getValue('sid'));
        _populateRefresh(d);
        d['date-tabs'] = _getDateTabs();
        d['market-tabs'] = _getMarketTabs();
        if (pid >= 40 && pid < 60) {
            d['region'] = d['sport'];
        }
        var sb = [];
        var cache = _data.caches[1];
        if (cache) {
            var ms = _getMarkets(cache, 't', 'live');
            if (ms && ms.length > 0) {
                sb.push('<div class="LiveMarket">');
                sb.push(ms);
                sb.push('</div>');
                d['class-section'] = 'Live';
            }
        }
        cache = _data.caches[2];
        if (cache) {
            ms = _getMarkets(cache, 't', 'nonlive');
            if (ms && ms.length > 0) {
                sb.push('<div class="NonLiveMarket">');
                sb.push(ms);
                sb.push('</div>');
                d['class-section'] = 'NonLive';
            }
        }
        d['markets'] = (sb.length > 0) ? sb.join('') : _template['msg-noevent'].getText();
        return _template['div-region'].getText(d);
    }

    function _getOutrights() {
        var pid = $T('od').getValue('pid');
        var re = $E('regions')[$T('od').getValue('rid')];
        if (!re) return null;
        var d = {};
        _populateSport(d, $T('od').getValue('sid'));
        _populateRegion(d, 0, re);
        _populateRefresh(d);
        d['date-tabs'] = _getDateTabs();
        if (pid >= 40 && pid < 60) {
            d['region'] = d['sport'];
        }
        var sb = [];
        var cache = _data.caches[4];
        if (cache) {
            var ms = _getOutrightMarkets(cache);
            if (ms && ms.length > 0) {
                sb.push('<div class="LiveMarket">');
                sb.push(ms);
                sb.push('</div>');
                d['class-section'] = 'Live';
            }
        }
        cache = _data.caches[5];
        if (cache) {
            ms = _getOutrightMarkets(cache);
            if (ms && ms.length > 0) {
                sb.push('<div class="NonLiveMarket">');
                sb.push(ms);
                sb.push('</div>');
                d['class-section'] = 'NonLive';
            }
        }
        d['markets'] = (sb.length > 0) ? sb.join('') : _template['msg-noevent'].getText();
        return _template['div-region'].getText(d);
    }

    function _getTournament() {
        var te = $E('tournaments')[$T('od').getValue('tid')];
        if (!te) return null;
        var d = {};
        _populateTournament(d, 0, te);
        _populateRefresh(d);
        var m = $M('fa');
        if (m && m.isFavouriteSelected && m.isFavouriteSelected('to', te[0])) {
            d['class-afa'] = 'Hide';
            d['class-rfa'] = null;
        } else {
            d['class-afa'] = null;
            d['class-rfa'] = 'Hide';
        }
        d['favourite'] = _template['div-favourite-t'].getText(d);
        d['date-tabs'] = _getDateTabs();
        d['market-tabs'] = _getMarketTabs();
        var sb = [];
        var cache = _data.caches[1];
        if (cache) {
            var ms = _getMarkets(cache, 't', 'live');
            if (ms && ms.length > 0) {
                sb.push('<div class="LiveMarket">');
                sb.push(ms);
                sb.push('</div>');
                d['class-section'] = 'Live';
            }
        }
        cache = _data.caches[4];
        if (cache) {
            ms = _getMarkets(cache, 't', 'live');
            if (ms && ms.length > 0) {
                sb.push('<div class="LiveMarket">');
                sb.push(ms);
                sb.push('</div>');
                d['class-section'] = 'Live';
            }
        }
        cache = _data.caches[2];
        if (cache) {
            ms = _getMarkets(cache, 't', 'nonlive');
            if (ms && ms.length > 0) {
                sb.push('<div class="NonLiveMarket">');
                sb.push(ms);
                sb.push('</div>');
                d['class-section'] = 'NonLive';
            }
        }
        cache = _data.caches[5];
        if (cache) {
            ms = _getMarkets(cache, 't', 'nonlive');
            if (ms && ms.length > 0) {
                sb.push('<div class="NonLiveMarket">');
                sb.push(ms);
                sb.push('</div>');
                d['class-section'] = 'NonLive';
            }
        }
        d['markets'] = (sb.length > 0) ? sb.join('') : _template['msg-noevent'].getText();
        return _template['div-tournament'].getText(d);
    }

    function _getEvent(d) {
        var arr = [];
        var tag = _getTagEvent($T('od').getValue('eid'), arr);
        if (!tag) return null;
        var e = tag[2];
        if (!d) d = {};
        d['c-id'] = 0;
        _populateEvent(d, 0, e);
        _populateRefresh(d);
        var hdp = _getHandicap(tag);
        d['hdp-type'] = hdp;
        d['hdp-h'] = (hdp == 1) ? 'Red' : 'Blue';
        d['hdp-a'] = (hdp == 2) ? 'Red' : 'Blue';
        var m = $M('fa');
        if (m && m.isFavouriteSelected && m.isFavouriteSelected('ev', e[0])) {
            d['class-afa'] = 'Hide';
            d['class-rfa'] = null;
        } else {
            d['class-afa'] = null;
            d['class-rfa'] = 'Hide';
        }
        d['favourite'] = _template['div-favourite-e'].getText(d);
        d['market-tabs'] = _getMarketTabs();
        var tevent = _template['div-event'];
        if (arr[1] == 1 || arr[1] == 8) {
            _populateLiveTime(d, tag, 0);
            _populateRedCards(d, tag, 0);
            tevent = _template['div-event-live'];
            d['event-livetop'] = _template['div-event-livetop'].getText(d);
        } else {
            var date = _getShowTime(e[5]);
            if (!isNaN(date)) {
                _populateDate(d, date);
                if (e[4] & 0x1) {
                    d['time'] = '**:**';
                } else {
                    d['time'] = _getTwoDigits(date.getHours()) + ':' + _getTwoDigits(date.getMinutes());
                }
            }
        }
        var sb = [];
        var cache = _data.caches[1];
        if (cache) {
            var ms = _getMarkets(cache, 'e');
            if (ms && ms.length > 0) {
                sb.push('<div class="LiveMarket">');
                sb.push(ms);
                sb.push('</div>');
            }
        }
        cache = _data.caches[2];
        if (cache) {
            ms = _getMarkets(cache, 'e');
            if (ms && ms.length > 0) {
                sb.push('<div class="NonLiveMarket">');
                sb.push(ms);
                sb.push('</div>');
            }
        }
        cache = _data.caches[3];
        if (cache) {
            ms = _getMarkets(cache, 'e');
            if (ms && ms.length > 0) {
                sb.push('<div class="NonLiveMarket">');
                sb.push(ms);
                sb.push('</div>');
            }
        }
        d['markets'] = (sb.length > 0) ? sb.join('') : _template['msg-noevent'].getText();
        return tevent.getText(d);
    }

    function _populateEventLiveCenter() {
        var d = {};
        _getEvent(d);
        _populateShowing(d);
        var tag = _getTagEvent($T('od').getValue('eid'));
        p = document.getElementById('panel-markets');
        if (p) {
            p.innerHTML = d['markets'];
            p = document.getElementById('panel-event-top');
            if (p) {
                p.innerHTML = _template['div-event-livetop'].getText(d);
            }
            if ($T('site').getValue('asi')) {
                $M('lc').updateEventInformation([$T('od').getValue('eid'), d['hdp-type'], d['period'], d['timer-current']]);
            }
        } else {
            p = document.getElementById('panel-odds-display');
            if (p) {
                d['event-livetop'] = _template['div-event-livetop'].getText(d);
                p.innerHTML = _template['div-event-livecenter'].getText(d);
                $M('lc').start([$T('od').getValue('eid'), d['hdp-type'], d['period'], d['timer-current']]);
            }
        }
    }

    function _populateShowing(d) {
        var arr = [];
        var tag = _getTagEvent($T('od').getValue('eid'), arr);
        if (tag) {
            var sportId = tag[0][0];
            var kit = tag[7];
            if (kit) {
                var homekit = kit[0];
                if (homekit) {
                    homekit = _getKitInfo(homekit.split(';'));
                }
                if (homekit) {
                    d['home-kit-class'] = 'TeamHome';
                    d['home-kit'] = homekit;
                } else {
                    if (kit[0] == "-1") {
                        d['home-kit-class'] = 'TeamHomeNoJersey';
                    } else {
                        if (sportId == 2) {
                            d['home-kit-class'] = 'TeamHome';
                            d['home-kit'] = _jerseyTemplate['sleveless-jersey-none'].getText({
                                'sleveless-jersey-none-cls': 'SlevelessJerseyHomeNone'
                            });
                        } else {
                            d['home-kit-class'] = 'TeamHomeNone';
                        }
                    }
                }
                var awaykit = kit[1];
                if (awaykit) {
                    awaykit = _getKitInfo(awaykit.split(';'));
                }
                if (awaykit) {
                    d['away-kit-class'] = 'TeamAway';
                    d['away-kit'] = awaykit;
                } else {
                    if (kit[1] == "-1") {
                        d['away-kit-class'] = 'TeamAwayNoJersey';
                    } else {
                        if (sportId == 2) {
                            d['away-kit-class'] = 'TeamAway';
                            d['away-kit'] = _jerseyTemplate['sleveless-jersey-none'].getText({
                                'sleveless-jersey-none-cls': 'SlevelessJerseyAwayNone'
                            });
                        } else {
                            d['away-kit-class'] = 'TeamAwayNone';
                        }
                    }
                }
            }
        }
    }

    function _getKitInfo(teamKit) {
        var kitType;
        switch (teamKit[0]) {
        case '1':
            kitType = _jerseyTemplate['jersey-plain'];
            break;
        case '2':
            kitType = _jerseyTemplate['jersey-half'];
            break;
        case '3':
            kitType = _jerseyTemplate['jersey-three-stripes'];
            break;
        case '4':
            kitType = _jerseyTemplate['jersey-horizontal-two-stripes'];
            break;
        case '5':
            kitType = _jerseyTemplate['jersey-sleveless-plain'];
            break;
        case '6':
            kitType = _jerseyTemplate['jersey-sleveless-two-stripes'];
            break;
        case '7':
            kitType = _jerseyTemplate['jersey-sleveless-three-stripes'];
            break;
        case '8':
            kitType = _jerseyTemplate['jersey-sleveless-horizontal-one-stripe'];
            break;
        case '9':
            kitType = _jerseyTemplate['jersey-sleveless-horizontal-two-stripes'];
            break;
        }
        var d = {};
        if (kitType) {
            var leftArm = teamKit[1];
            if (leftArm) {
                d['left-arm-color'] = leftArm;
            }
            var rightArm = teamKit[2];
            if (rightArm) {
                d['right-arm-color'] = rightArm;
            }
            var body = teamKit[3];
            if (body) {
                d['body-color'] = body;
            }
            var stripes = teamKit[4];
            if (stripes) {
                d['stripes-color'] = stripes;
            }
            if (kitType) {
                return kitType.getText(d);
            }
        }
        return null;
    }
    this.draw = function () {
        var bc = _getBreadcrumb();
        var p = document.getElementById('panel-breadcrumb');
        if (p) {
            if (bc) {
                p.style.display = 'block';
                p.innerHTML = bc;
            } else {
                p.style.display = 'none';
                p.innerHTML = '';
            }
        }
        p = document.getElementById('panel-iconbar');
        var ib = _getIconBar();
        if (p) {
            p.innerHTML = (ib) ? ib : '';
        }
        var pid = $T('od').getValue('pid');
        if (pid != 25) {
            $M('ls').onClear();
        }
        _target.refreshCount = 0;
        var od;
        switch ($T('od').getValue('pid')) {
        case 11:
        case 21:
            od = _getSport();
            break;
        case 31:
            od = _getMixParlay();
            break;
        case 12:
        case 22:
        case 40:
        case 41:
        case 50:
        case 51:
        case 60:
        case 70:
            od = _getRegion();
            break;
        case 13:
        case 23:
        case 43:
        case 53:
        case 63:
        case 73:
            od = _getTournament();
            break;
        case 14:
        case 24:
        case 44:
        case 54:
        case 64:
        case 74:
            od = _getOutrights();
            break;
        case 25:
        case 55:
        case 75:
            if ($E('livevideos')[$T('od').getValue('eid')] || $E('running')[$T('od').getValue('eid')]) {
                _populateEventLiveCenter();
                return;
            }
        case 15:
        case 35:
        case 45:
        case 65:
            od = _getEvent();
            break;
        case 2:
        default:
            od = _getHome();
            break;
        }
        p = document.getElementById('panel-odds-display');
        if (p) {
            p.innerHTML = (od) ? od : '';
        }
    }
}

function __EuroModelOddsDisplay(sportOrder, refreshRate, mpRefreshRate, seoHlDelay) {
    var _self = this;
    var _template = tilib_GenerateTemplates($P.getTemplate('od'));
    var _jerseyTemplate = tilib_GenerateTemplates($P.getTemplate('vi'));
    var _elemTranslation = $E('translation');
    var _data = {
        caches: {},
        dcounts: {},
        mcounts: {},
        stab: 0
    };
    var _target = {
        refreshCount: 0,
        refreshButtons: null
    };
    var _syn = {
        initiated: false,
        drawing: false,
        cooldownCount: 0,
        failureCount: 0,
        refreshRate: refreshRate,
        mpRefreshRate: mpRefreshRate,
        refreshCount: $T('site').getValue('seo') ? _getRefreshRate(refreshRate, mpRefreshRate) : 0,
        closing: false
    };
    var _seoHLSec = parseInt(seoHlDelay);
    var _hlInit = true;
    var _drawing = new __EuroModelOddsDisplayDrawing(sportOrder, _template, _data, _target, _syn, _jerseyTemplate);
    var od_Live_Video_Name = ["sbolivevideo0", "sbolivevideo1", "sbolivevideo2", "sbolivevideo3", "sbolivevideo4"];
    var od_Live_Video_Ref = [];
    var od_Live_Video_Count = [-1];
    this.getTagEvent = function (eventId) {
        return _getTagEvent(eventId);
    }
    this.onPageChanged = function () {
        _syn.refreshCount = _getRefreshRate();
    }

    function _getRefreshRate(rate, mprate) {
        var pid = $T('od').getValue('pid');
        if (pid >= 30 && pid <= 35) {
            return (mprate) ? mprate : _syn.mpRefreshRate;
        } else {
            return (rate) ? rate : _syn.refreshRate;
        }
    }

    function _updateVersion(version, renew) {
        var sev = $T('od').getValue('sev');
        if (version && (version >= sev || renew)) {
            if (!sev || renew) {
                _data.caches = {};
                _data.dcounts = {};
                _data.mcounts = {};
                var m = $M('hl');
                if (m && m.stop && (_seoHLSec < 1)) {
                    m.stop();
                }
                m = $M('lc');
                if (m && m.stop) {
                    m.stop();
                }
            }
            _syn.initiated = true;
            $T('od').setValue('oev', version);
            $T('od').setValue('sev', version);
            return true;
        }
        return false;
    }
    this.onIdle = function (version) {
        $M('ms').onOddsDrawed();
        _updateVersion(version);
        var updated = false;
        for (var cid in _data.caches) {
            var ce = _data.caches[cid];
            if (ce && ce.clearPAIs()) {
                updated = true;
            }
        }
        if (updated) {
            _draw();
        }
        _syn.drawing = false;
    };
    this.onUpdate = function (d) {
        $M('ms').onOddsDrawed();
        var renew = (d[1] || !$T('od').getValue('sev')) ? 1 : 0;
        var ps = $T('od').getValue('ps');
        if (_updateVersion(d[0], renew)) {
            var us = d[2];
            if (us) {
                var c = us.length;
                for (var i = 0; i < c; ++i) {
                    var u = us[i];
                    if (u) {
                        var cid = u[0];
                        var ce = _data.caches[cid];
                        if (cid == 4 || cid == 5) {
                            if (!ce) {
                                _data.caches[cid] = ce = new od_CacheOutright(cid);
                            }
                            ce.update(u[1], u[2]);
                        } else {
                            if (!ce) {
                                _data.caches[cid] = ce = new od_CacheEvent(cid);
                            }
                            ce.update(u[1], u[2], u[3], ps);
                            if (cid == 6 && !_data.stab) {
                                var ses = $E('sports');
                                var sports = ce.getSports();
                                for (var sid in ses) {
                                    var se = ses[sid];
                                    if (se && sports[sid]) {
                                        _data.stab = sid;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            var dcounts = d[3];
            if (dcounts) {
                _data.dcounts = dcounts;
            }
            var mcounts = d[4];
            if (mcounts) {
                _data.mcounts = mcounts;
            }
            _data.displaySubmarket = d[5];
            if (_relocate()) {
                _syn.drawing = false;
                return;
            }
            _draw();
            _syn.drawing = false;
            if (renew) {
                var pid = $T('od').getValue('pid');
                if (pid == 2 || pid == 11 || pid == 40) {
                    var m = $M('hl');
                    if (m && m.start && (_seoHLSec < 1)) {
                        m.start();
                    }
                }
            }
        }
        if (_hlInit) {
            _nox_highlights.init();
            _hlInit = false;
        }
    };
    this.onTime = function () {
        if (_syn.closing) {} else if (_syn.cooldownCount) {
            _syn.cooldownCount--;
        } else {
            if (_syn.drawing) {
                if (_syn.failureCount > 3) {
                    _syn.drawing = false;
                } else {
                    _syn.failureCount++;
                }
            } else if (_syn.refreshCount > 0) {
                _drawRefreshButtons();
                --_syn.refreshCount;
            } else {
                _syn.refreshCount = _getRefreshRate();
                _syn.drawing = true;
                if (_syn.failureCount) {
                    _syn.failureCount = 0;
                }
                _submit();
                _setCoolDown();
                _drawRefreshButtons();
            }
        }
        if (_seoHLSec > 0) {
            _seoHLSec--;
        }
    };
    this.onRefresh = function () {
        if (!_syn.closing && !_syn.cooldownCount) {
            if (_syn.drawing) {
                if (_syn.failureCount > 3) {
                    _syn.drawing = false;
                } else {
                    _syn.failureCount++;
                }
            } else {
                _syn.refreshCount = _getRefreshRate();
                _syn.drawing = true;
                if (_syn.failureCount) {
                    _syn.failureCount = 0;
                }
                _submit();
                _setCoolDown();
                _drawRefreshButtons();
            }
        }
    };

    function _relocate(fpid) {
        var force = (fpid) ? true : false;
        var pid = (fpid) ? fpid : $T('od').getValue('pid');
        switch (pid) {
        case 15:
        case 25:
        case 35:
        case 45:
        case 55:
        case 65:
        case 75:
            var eid = $T('od').getValue('eid');
            if (!eid) return false;
            var tag = _getTagEvent(eid);
            if (tag) return false;
            if (pid == 35) {
                return $M('euro').goMixParlay($T('od').getValue('sid'));
            } else if (pid > 40 && pid <= 75) {
                return _relocate(pid - 5);
            } else {
                return _relocate(pid - 4);
            }
        case 13:
        case 23:
            var tid = $T('od').getValue('tid');
            var te = $E('tournaments')[tid];
            if (te) {
                if (force) {
                    switch (pid) {
                    case 13:
                        return $M('euro').goTournament(tid);
                    case 23:
                        return $M('euro').goLiveTournament(tid);
                    }
                } else {
                    return false;
                }
            } else {
                return _relocate(pid - 1);
            }
        case 12:
        case 22:
        case 40:
        case 50:
        case 60:
        case 70:
            var rid = $T('od').getValue('rid');
            var sid = $T('od').getValue('sid');
            if (sid && $E('sports')[sid]) {
                if (rid && $E('regions')[rid]) {
                    if (force) {
                        if (pid == 22) {
                            return $M('euro').goLiveRegion(sid, rid);
                        } else if (pid == 40) {
                            return $M('euro').goBigEvent();
                        } else if (pid == 50) {
                            return $M('euro').goLiveBigEvent();
                        } else if (pid == 60) {
                            return $M('euro').goEufaEuroEvent();
                        } else if (pid == 70) {
                            return $M('euro').goLiveEufaEuroEvent();
                        } else {
                            return $M('euro').goRegion(sid, rid);
                        }
                    } else {
                        return false;
                    }
                } else if (pid == 60 || pid == 70) {
                    return _relocate(10);
                } else {
                    return _relocate(pid - 1);
                }
            } else {
                return _relocate(10);
            }
            break;
        case 11:
        case 21:
            sid = $T('od').getValue('sid');
            if (sid && $E('sports')[sid]) {
                if (force) {
                    if (pid == 21) {
                        return $M('euro').goLiveSport(sid);
                    } else {
                        return $M('euro').goSport(sid);
                    }
                } else {
                    return false;
                }
            } else {
                return _relocate(10);
            }
            break;
        case 10:
            if (force) {
                return $M('euro').goHome();
            }
            break;
        }
        return false;
    }

    function _getTagEvent(eid) {
        for (var cid in _data.caches) {
            var c = _data.caches[cid];
            if (c) {
                var tag = c.getTag(eid);
                if (tag) {
                    return tag;
                }
            }
        }
        return null;
    }

    function _onOpenCloseMarket(cid, mid) {
        var id = 'od-ma-' + cid + '-' + mid;
        var e = document.getElementById(id);
        if (e) {
            var pid = $T('od').getValue('pid');
            if ((pid == 11 || pid == 21 || pid == 31) && $T('od').getValue('sid') == 1) {
                id += '-s-1';
            }
            var state = $S('od');
            switch (state[id]) {
            case 'Closed':
                state[id] = 'Open';
                e.className = e.className.replace('Closed', 'Open');
                break;
            case 'Open':
            default:
                state[id] = 'Closed';
                e.className = e.className.replace('Open', 'Closed');
                break;
            }
        }
    }

    function _onOpenCloseOutright(sid, rid) {
        var id = 'od-or-' + sid + '-' + rid;
        var e = document.getElementById(id);
        if (e) {
            var state = $S('od');
            switch (state[id]) {
            case 'Closed':
                state[id] = 'Open';
                e.className = e.className.replace('Closed', 'Open');
                break;
            case 'Open':
            default:
                state[id] = 'Closed';
                e.className = e.className.replace('Open', 'Closed');
                break;
            }
        }
    }
    this.goDate = function (dt) {
        if (dt != undefined) {
            dt = parseInt(dt);
            if (dt > 0 && dt <= 9) {
                switch ($T('od').getValue('pid')) {
                case 11:
                    return $M('euro').goSport($T('od').getValue('sid'), dt);
                case 12:
                    return $M('euro').goRegion($T('od').getValue('sid'), $T('od').getValue('rid'), dt);
                case 13:
                    return $M('euro').goTournament($T('od').getValue('tid'), dt);
                case 14:
                    return $M('euro').goOutright($T('od').getValue('sid'), $T('od').getValue('rid'), dt);
                case 20:
                case 21:
                    return $M('euro').goLiveSport($T('od').getValue('sid'), dt);
                case 22:
                    return $M('euro').goLiveRegion($T('od').getValue('sid'), $T('od').getValue('rid'), dt);
                case 23:
                    return $M('euro').goLiveTournament($T('od').getValue('tid'), dt);
                case 24:
                    return $M('euro').goLiveOutright($T('od').getValue('sid'), $T('od').getValue('rid'), dt);
                case 30:
                case 31:
                    return $M('euro').goMixParlay($T('od').getValue('sid'), dt);
                case 40:
                    return $M('euro').goBigEvent($T('od').getValue('sid'), dt);
                case 41:
                    return $M('euro').goBigEventSport($T('od').getValue('sid'), dt);
                case 43:
                    return $M('euro').goBigEventTournament($T('od').getValue('tid'), dt);
                case 44:
                    return $M('euro').goBigEventOutright($T('od').getValue('sid'), $T('od').getValue('rid'), dt);
                case 51:
                    return $M('euro').goLiveBigEventSport($T('od').getValue('sid'), dt);
                case 53:
                    return $M('euro').goLiveBigEventTournament($T('od').getValue('tid'), dt);
                case 54:
                    return $M('euro').goLiveBigEventOutright($T('od').getValue('sid'), $T('od').getValue('rid'), dt);
                case 60:
                    return $M('euro').goEufaEuroEvent($T('od').getValue('sid'), dt);
                case 63:
                    return $M('euro').goEufaEuroEventTournament($T('od').getValue('tid'), dt);
                case 64:
                    return $M('euro').goEufaEuroOutright($T('od').getValue('sid'), $T('od').getValue('rid'), dt);
                }
            }
        }
        return false;
    };
    this.goMarket = function (mt) {
        if (mt != undefined) {
            mt = parseInt(mt);
            if (mt > 0 && mt < 5) {
                switch ($T('od').getValue('pid')) {
                case 31:
                    return $M('euro').goMixParlay($T('od').getValue('sid'), $T('od').getValue('dt'), mt);
                case 41:
                    return $M('euro').goBigEventSport($T('od').getValue('sid'), $T('od').getValue('dt'), mt);
                case 51:
                    return $M('euro').goLiveBigEventSport($T('od').getValue('sid'), $T('od').getValue('dt'), mt);
                case 12:
                    return $M('euro').goRegion($T('od').getValue('sid'), $T('od').getValue('rid'), $T('od').getValue('dt'), mt);
                case 22:
                    return $M('euro').goLiveRegion($T('od').getValue('sid'), $T('od').getValue('rid'), $T('od').getValue('dt'), mt);
                case 13:
                    return $M('euro').goTournament($T('od').getValue('tid'), $T('od').getValue('dt'), mt);
                case 23:
                    return $M('euro').goLiveTournament($T('od').getValue('tid'), $T('od').getValue('dt'), mt);
                case 43:
                    return $M('euro').goBigEventTournament($T('od').getValue('tid'), $T('od').getValue('dt'), mt);
                case 53:
                    return $M('euro').goLiveBigEventTournament($T('od').getValue('tid'), $T('od').getValue('dt'), mt);
                case 15:
                case 25:
                case 35:
                case 45:
                case 55:
                    return this.goEvent($T('od').getValue('eid'), mt);
                case 60:
                    return $M('euro').goRegion($T('od').getValue('sid'), $T('od').getValue('rid'), $T('od').getValue('dt'), mt);
                case 63:
                    return $M('euro').goEufaEuroEventTournament($T('od').getValue('tid'), $T('od').getValue('dt'), mt);
                case 70:
                    return $M('euro').goLiveRegion($T('od').getValue('sid'), $T('od').getValue('rid'), $T('od').getValue('dt'), mt);
                case 73:
                    return $M('euro').goLiveEufaEuroEventTournament($T('od').getValue('tid'), $T('od').getValue('dt'), mt);
                }
            }
        }
        return false;
    };
    this.goMixParlaySport = function (sid) {
        return $M('euro').goMixParlay(sid, $T('od').getValue('dt'));
    };
    this.moveTo = function (eid, mt, pid) {
        var tag = _getTagEvent(eid);
        if (tag) {
            var e = tag[2];
            var name = [];
            name.push($Code(e[1]));
            name.push(_elemTranslation['vs'][1]);
            name.push($Code(e[2]));
            if (!pid) pid = $T('od').getValue('pid');
            if (pid >= 70) {
                pid = 75;
            } else if (pid >= 60) {
                pid = 65;
            } else if (pid >= 50) {
                pid = 55;
            } else if (pid >= 40) {
                pid = 45;
            } else if (pid >= 30) {
                pid = 35;
            } else if (pid >= 20) {
                pid = 25;
            } else {
                pid = 15;
            }
            return $M('euro').moveTo(pid, tag[0][0], tag[1][3], tag[1][0], eid, name.join(''), 0, mt, true);
        }
        return null;
    };
    this.goEvent = function (eid, mt, pid) {
        var token = this.moveTo(eid, mt, pid);
        if (token) {
            if (mt === undefined) token.setValue('mt', 4);
            this.onReload(token);
            return true;
        }
        return false;
    };
    this.goFavEvent = function (tid, eid, home, away) {
        var te = $E('tournaments')[tid];
        if (te) {
            var name = [];
            name.push($Code(home));
            name.push(_elemTranslation['vs'][1]);
            name.push($Code(away));
            var token = $M('euro').moveTo(15, te[2], te[3], tid, eid, name.join(''), 0, 4);
            if (token) {
                this.onReload(token);
                return true;
            }
        }
        return false;
    };
    this.onLiveCenter = function (eid) {
        this.goEvent(eid, undefined, 25);
    };
    this.goStatistics = function (eid) {
        var tag = _getTagEvent(eid);
        if (tag) {
            var e = tag[2];
            if (e[9]) {
                var sb = [];
                sb.push('/');
                sb.push($T('site').getValue('lang'));
                sb.push('/statistics/');
                sb.push(e[0]);
                sb.push('/');
                sb.push($Code(e[1]));
                sb.push(_elemTranslation['vs'][1]);
                sb.push($Code(e[2]));
                window.open(sb.join(''), 'Statistics', 'scrollbars=no,resizable=no,width=1000,height=600');
                return true;
            }
        }
        return false;
    };
    this.onShowHide = function (id, show) {
        var e = document.getElementById(id);
        if (show) {
            e.className = '';
        } else {
            e.className = 'Hide';
        }
    };
    this.onMouseOverOut = function (event, out) {
        if (!event) event = window.event;
        var e = event.srcElement ? event.srcElement : event.target;
        while (e) {
            var id = e.id;
            e = e.parentNode;
            if (!id) continue;
            var atom = id.split(':');
            var count = atom.length;
            if (count >= 3 && atom[0] == 'bu' && atom[1] == 'od') {
                switch (atom[2]) {
                case 'or':
                    if (count >= 4) {
                        e = document.getElementById('od-ex-st-' + atom[3]);
                        if (e) {
                            e.style.visibility = (out) ? 'hidden' : 'visible';
                            return true;
                        }
                    }
                    break;
                }
            }
        }
        return false;
    }
    this.onClick = function (event) {
        if (!event) event = window.event;
        if (!_onClick(event)) {
            event.returnValue = false;
            return false;
        }
        return true;
    };

    function _onClick(event) {
        var e = event.srcElement ? event.srcElement : event.target;
        while (e) {
            var id = e.id;
            e = e.parentNode;
            if (!id) continue;
            var atom = id.split(':');
            var count = atom.length;
            if (count >= 3 && atom[0] == 'bu' && atom[1] == 'od') {
                switch (atom[2]) {
                case 'oc':
                    if (count >= 4) {
                        switch (atom[3]) {
                        case 'ma':
                            if (count >= 6) {
                                _onOpenCloseMarket(atom[4], atom[5]);
                                return false;
                            }
                            break;
                        case 'or':
                            if (count >= 6) {
                                _onOpenCloseOutright(atom[4], atom[5]);
                                return false;
                            }
                            break;
                        }
                    }
                    break;
                case 're':
                    if (count >= 4) {
                        var refreshId = atom[3];
                        var refreshDiv = document.getElementById('refresh-icon-' + refreshId);
                        if (refreshDiv) {
                            refreshDiv.className = 'league-refresh-icon-rotate';
                            setTimeout(function () {
                                refreshDiv.className = 'league-refresh-icon';
                            }, 3000);
                        }
                    }
                    _self.onRefresh();
                    return false;
                case 'go':
                    if (count >= 4) {
                        if ($T('site').getValue('seo')) {
                            switch (atom[3]) {
                            case 'st':
                                if (count >= 5) {
                                    return !_self.goStatistics(atom[4]);
                                }
                                break;
                            case 'mt':
                                if (count >= 5) {
                                    return !_self.goMarket(atom[4]);
                                }
                                break;
                            case 'tv':
                                if (count >= 5) {
                                    _self.onLiveTV(atom[4]);
                                    return false;
                                }
                                break;
                            }
                        } else {
                            switch (atom[3]) {
                            case 'ho':
                                return !$M('euro').goHome();
                            case 'lb':
                                return !$M('euro').goLiveBetting();
                            case 'mp':
                                return !$M('euro').goMixParlay();
                            case 'sp':
                                if (count >= 5) {
                                    return !$M('euro').goSport(atom[4]);
                                }
                                break;
                            case 're':
                                if (count >= 6) {
                                    return !$M('euro').goRegion(atom[4], atom[5]);
                                }
                                break;
                            case 'to':
                                if (count >= 5) {
                                    return !$M('euro').goTournament(atom[4]);
                                }
                                break;
                            case 'ev':
                                if (count >= 5) {
                                    return !_self.goEvent(atom[4]);
                                }
                                break;
                            case 'lsp':
                                if (count >= 5) {
                                    return !$M('euro').goLiveSport(atom[4]);
                                }
                                break;
                            case 'lre':
                                if (count >= 6) {
                                    return !$M('euro').goLiveRegion(atom[4], atom[5]);
                                }
                                break;
                            case 'lto':
                                if (count >= 5) {
                                    return !$M('euro').goLiveTournament(atom[4]);
                                }
                                break;
                            case 'lev':
                                if (count >= 5) {
                                    return !_self.goEvent(atom[4], $T('od').getValue('mt'), 25);
                                }
                                break;
                            case 'be':
                                return !$M('euro').goBigEvent();
                            case 'besp':
                                if (count >= 5) {
                                    return !$M('euro').goBigEventSport(atom[4]);
                                }
                                break;
                            case 'beto':
                                if (count >= 5) {
                                    return !$M('euro').goBigEventTournament(atom[4]);
                                }
                                break;
                            case 'beev':
                                if (count >= 5) {
                                    return !_self.goEvent(atom[4]);
                                }
                                break;
                            case 'eeto':
                                if (count >= 5) {
                                    return !$M('euro').goEufaEuroEventTournament(atom[4]);
                                }
                                break;
                            case 'eeev':
                                if (count >= 5) {
                                    return !_self.goEvent(atom[4]);
                                }
                                break;
                            case 'ee':
                                return !$M('euro').goEufaEuroEvent();
                                break;
                            case 'lee':
                                return !$M('euro').goLiveEufaEuroEvent();
                                break;
                            case 'leeto':
                                if (count >= 5) {
                                    return !$M('euro').goLiveEufaEuroEventTournament(atom[4]);
                                }
                                break;
                            case 'lbe':
                                return !$M('euro').goLiveBigEvent();
                            case 'lbesp':
                                if (count >= 5) {
                                    return !$M('euro').goLiveBigEventSport(atom[4]);
                                }
                                break;
                            case 'lbeto':
                                if (count >= 5) {
                                    return !$M('euro').goLiveBigEventTournament(atom[4]);
                                }
                                break;
                            case 'lbeev':
                                if (count >= 5) {
                                    return !_self.goEvent(atom[4]);
                                }
                                break;
                            case 'st':
                                if (count >= 5) {
                                    return !_self.goStatistics(atom[4]);
                                }
                                break;
                            case 'dt':
                                if (count >= 5) {
                                    return !_self.goDate(atom[4]);
                                }
                                break;
                            case 'mt':
                                if (count >= 5) {
                                    return !_self.goMarket(atom[4]);
                                }
                                break;
                            case 'tv':
                                if (count >= 5) {
                                    _self.onLiveTV(atom[4]);
                                    return false;
                                }
                                break;
                            case 'lc':
                                if (count >= 5) {
                                    return !_self.goEvent(atom[4], undefined, 25);
                                }
                                break;
                            }
                        }
                    }
                    break;
                case 'st':
                    if (count >= 5) {
                        if (!_data.caches || !_data.caches[6]) {
                            return $M('euro').goSport(atom[4]);
                        } else {
                            _data.stab = parseInt(atom[4]);
                            _draw();
                            return false;
                        }
                    }
                    break;
                case 'afa':
                    if (count >= 4) {
                        switch (atom[3]) {
                        case 'to':
                        case 'ev':
                            if (count >= 5) {
                                return !$M('fa').add(atom[3], atom[4]);
                            }
                            break;
                        }
                    }
                    break;
                case 'rfa':
                    if (count >= 4) {
                        switch (atom[3]) {
                        case 'to':
                        case 'ev':
                            if (count >= 5) {
                                return !$M('fa').remove(atom[3], atom[4]);
                            }
                            break;
                        }
                    }
                    break;
                case 'mp':
                    if (count >= 4) {
                        switch (atom[3]) {
                        case 'sp':
                            if (count >= 5 && !$T('site').getValue('seo')) {
                                return !_self.goMixParlaySport(atom[4]);
                            }
                            break;
                        case 'dt':
                            if (count >= 5 && !$T('site').getValue('seo')) {
                                return !_self.goDate(atom[4]);
                            }
                            break;
                        }
                    }
                    break;
                case 'am':
                case 'rm':
                    if (count >= 4) {
                        _self.onToggleMS(atom[3]);
                        return false;
                    }
                    break;
                }
            }
        }
        return true;
    };
    this.onToggleMS = function (mid) {
        var me = $E('market-displays')[mid];
        if (me) {
            var flag = me[2];
            if (flag) {
                var token = $T('od');
                var ms = token.getValue('ms');
                var new_ms = ms ^ flag;
                if (token.getValue('mt') == 1) {
                    token = token.clone();
                    token.setValue('ms', new_ms);
                    this.onReload(token);
                    var e = document.getElementById('od-msi-' + mid);
                    if (e) {
                        e.checked = (ms & flag) ? true : false;
                    }
                } else {
                    token.setValue('ms', new_ms);
                    _draw();
                }
            }
        }
        return false;
    };
    this.onPrice = function (tid, oid, option, price) {
        if (tid == 'o') option = parseInt(option);
        $M('bs').onAddBetSlip(tid, oid, option, price);
    };
    this.onOptionSelected = function (tid, key, selected) {
        var pid = $T('od').getValue('pid');
        var id = 'od-' + tid + '-' + key;
        if (pid == 2) {
            var p = document.getElementById('panel-odds-display');
            var ds = p.getElementsByTagName('a');
            var c = ds.length;
            for (var i = 0; i < c; ++i) {
                var e = ds[i];
                if (e.id == id) {
                    if (selected) {
                        e.className = e.className + ' OddsSel';
                    } else {
                        e.className = e.className.replace('OddsSel', '');
                    }
                }
            }
        } else {
            e = document.getElementById(id);
            if (e) {
                if (selected) {
                    e.className = e.className + ' OddsSel';
                } else {
                    e.className = e.className.replace('OddsSel', '');
                }
            }
        }
        var m = $M('hl');
        if (m && m.onOptionSelected) {
            m.onOptionSelected(tid, key, selected);
        }
    };
    this.onDraw = function () {
        _draw();
    };
    this.onDrawOR = function () {
        var ce = _data.caches[4];
        if (ce) {
            ce.updateTournament();
        }
        ce = _data.caches[5];
        if (ce) {
            ce.updateTournament();
        }
        _draw();
    };
    this.onFavouriteSelected = function (type, id, selected) {
        var aid = 'bu:od:afa:' + type + ':' + id;
        var rid = 'bu:od:rfa:' + type + ':' + id;
        var p = document.getElementById('panel-odds-display');
        var ae = document.getElementById(aid);
        var re = document.getElementById(rid);
        if (p && ae && re) {
            var ds = p.getElementsByTagName('div');
            var c = ds.length;
            for (var i = 0; i < c; ++i) {
                var d = ds[i];
                if (d.id == aid) {
                    if (selected) {
                        d.className = 'IconFav Hide';
                    } else {
                        d.className = 'IconFav';
                    }
                } else if (d.id == rid) {
                    if (selected) {
                        d.className = 'IconFavSel';
                    } else {
                        d.className = 'IconFavSel Hide';
                    }
                }
            }
        }
    };
    this.onSortStyle = function (sid) {
        var sort = document.getElementById("tb-sorting");
        if (sort) {
            switch (sid) {
            case 1:
                sort.className = 'sort-1';
                break;
            case 2:
                sort.className = 'sort-2';
                break;
            default:
                sort.className = 'sort-1';
                break;
            }
        }
        if (sid != $T('site').getValue('sort')) {
            $T('site').setValue('sort', sid);
            for (var i in _data.caches) {
                var c = _data.caches[i];
                if (c && c.normalize) {
                    c.normalize();
                }
            }
            _draw();
        }
    };
    this.onPriceStyle = function (psid) {
        var odds = document.getElementById("tb-price-style");
        if (odds) {
            switch (psid) {
            case 1:
                odds.className = 'odds-type-1';
                break;
            case 2:
                odds.className = 'odds-type-2';
                break;
            case 4:
                odds.className = 'odds-type-4';
                break;
            default:
                odds.className = 'odds-type-4';
                break;
            }
        }
        if (psid != $T('od').getValue('ps')) {
            var token = $T('od').clone();
            token.setValue('ps', psid);
            this.onReload(token);
        }
    };
    this.onReload = function (token) {
        _syn.refreshCount = _getRefreshRate();
        _syn.drawing = true;
        _syn.failureCount = 0;
        if (!token) token = $T('od').clone();
        token.setValue('sev', 0);
        if (_submit(token)) {
            _setCoolDown();
            return true;
        }
        return false;
    };
    this.onLiveTV = function (eid) {
        var l = $T('site').getValue('lang');
        var url = [];
        url.push('/');
        url.push(l);
        url.push('/page/video?event=');
        url.push(eid);
        od_Live_Video_Count[0]++;
        for (var i = 0; i < 5; ++i) {
            if (_windowAvailable(i)) {
                od_Live_Video_Ref[i] = _openLiveTV(url.join(''), od_Live_Video_Name[i]);
                break;
            }
        }
        if (i == 5) {
            i = od_Live_Video_Count[0] % 5;
            od_Live_Video_Ref[i] = _openLiveTV(url.join(''), od_Live_Video_Name[i]);
        }
    }
    this.onTVChannel = function (isNewTVEnabled) {
        var size;
        if (isNewTVEnabled === 1) {
            size = {
                'sb': 'yes',
                'w': 670,
                'h': 600
            };
        } else {
            size = {
                'sb': 'yes',
                'w': 631,
                'h': 600
            }
        }
        var sportId = $T('od').getValue('sid');
        tilib_PopUp('tvchannel', '/' + $T('site').getValue('lang') + '/page/redirect?page=tvchannel' + '&sport=' + sportId, size);
    };

    function _openLiveTV(url, name) {
        var userAgent = navigator.userAgent.toLowerCase();
        var w, h;
        if (userAgent.indexOf("firefox") > -1) {
            w = 414 + 371;
            h = 373;
        } else if (userAgent.indexOf("msie") > -1) {
            if (userAgent.indexOf("msie 6.0") > -1) {
                w = 413 + 371;
                h = 373;
            } else {
                w = 414 + 371;
                h = 372;
            }
        } else if (userAgent.indexOf("chrome") > -1) {
            w = 415 + 371;
            h = 377;
        } else if (userAgent.indexOf("applewebkit") > -1) {
            w = 414 + 371;
            h = 375;
        } else {
            w = 414 + 371;
            h = 375;
        }
        return tilib_PopUp(name, url, {
            'sb': 'no',
            'w': w,
            'h': h
        });
    }

    function _windowAvailable(index) {
        if (od_Live_Video_Ref != undefined && od_Live_Video_Ref[index] && od_Live_Video_Ref[index].open && !od_Live_Video_Ref[index].closed) {
            return false;
        }
        if ($P.getWindow(od_Live_Video_Name[index])) {
            return false;
        }
        return true;
    }

    function _setCoolDown() {
        _syn.cooldownCount = 2;
        _syn.refreshCount = _getRefreshRate();
    }

    function _submit(token) {
        var sb = [];
        sb.push('/');
        sb.push($T('site').getValue('lang'));
        sb.push('/data/event?ts=');
        sb.push($T('site').getValue('ts'));
        sb.push('&tk=');
        sb.push((token ? token : $T('od')).getToken());
        var h = $M('euro').getHash();
        if (h) {
            sb.push('&ex=');
            sb.push(h);
            if (!_syn.initiated || g_MenuSportFireEvent) {
                sb.push('&ac=1');
            }
        } else if (token) {
            if (!_syn.initiated || g_MenuSportFireEvent || token.getValue('pid') != $T('od').getValue('pid') || token.getValue('sid') != $T('od').getValue('sid') || token.getValue('rid') != $T('od').getValue('rid') || token.getValue('tid') != $T('od').getValue('tid') || token.getValue('eid') != $T('od').getValue('eid')) {
                sb.push('&ac=1');
            } else if (token.getValue('dt') != $T('od').getValue('dt')) {
                sb.push('&ac=2');
            } else if (token.getValue('mt') != $T('od').getValue('mt')) {
                sb.push('&ac=3');
            } else if (token.getValue('ms') != $T('od').getValue('ms')) {
                sb.push('&ac=4');
            } else if (token.getValue('ps') != $T('od').getValue('ps')) {
                sb.push('&ac=5');
            }
        } else if (!_syn.initiated || g_MenuSportFireEvent) {
            sb.push('&ac=1');
        }
        if ((token ? token : $T('od')).getValue('pid') == 25) {
            sb.push('&vs=');
            sb.push($M('ls').getState());
        }
        return $P.sendRequest('od', sb.join(''));
    }

    function _draw() {
        var pid = $T('od').getValue('pid');
        var eid = $T('od').getValue('eid');
        if (eid && (pid == 5 || pid == 7 || pid == 9)) {
            var tag = _getTagEvent(eid);
            if (!tag) {
                switch (pid) {
                case 5:
                    $M('euro').goTournament($T('od').getValue('tid'));
                    return;
                case 7:
                    $M('euro').goLiveBetting();
                    return;
                case 9:
                    $M('euro').goMixParlay();
                    return;
                }
            }
        }
        _drawing.draw();
        _target.refreshButtons = null;
    }

    function _drawRefreshButtons() {
        var tspanr = (_syn.cooldownCount) ? _template['refresh-text-wait'] : _template['refresh-text'];
        var refresh = tspanr.getText({
            'count': _syn.refreshCount
        });
        if (!_target.refreshButtons) {
            _target.refreshButtons = [];
            var c = _target.refreshCount;
            for (var i = 0; i < c; ++i) {
                var e = document.getElementById('bu:od:re:' + i);
                if (e) {
                    _target.refreshButtons.push(e);
                }
            }
        }
        if (_target.refreshButtons) {
            var rc = _target.refreshButtons.length;
            for (var ri = 0; ri < rc; ++ri) {
                var rb = _target.refreshButtons[ri];
                if (rb) {
                    rb.innerHTML = refresh;
                }
            }
        }
    }
}

function lc_EuroModel(url, refreshRate, infoUrl) {
    var _translation = $P.getTranslation('lc');
    var _url = url;
    var _infoUrl = infoUrl;
    var _template = tilib_GenerateTemplates($P.getTemplate('lc'));
    var _target = [];
    var _syn = {
        rsynid: -1,
        mode: 0,
        getNewStatistic: false,
        refreshRate: refreshRate,
        refreshCount: refreshRate,
        running: false,
        initiated: false
    };
    var eventInfo = [];
    var gameState;
    var goals;
    var redCards;
    var stats;
    var livecourt;
    this.start = function (data) {
        reinitialize();
        _syn.running = true;
        this.updateEventInformation(data);
        var param = eventInfo[0] + ',' + (_syn.getNewStatistic ? 's,' : ',') + _syn.mode + ',' + _syn.rsynid;
        _submit('token=' + param);
    }
    this.stop = function () {
        _syn.running = false;
        _syn.rsynid = -1;
        reinitialize();
    }
    this.onUpdateData = function (data) {
        if (data) {
            var count = 0;
            var redraw = false;
            if (data[0]) {
                if (_syn.rsynid <= 0) {
                    redraw = true;
                }
                _syn.rsynid = data[0];
            }
            if (data[1]) {
                updateGameState(data[1]);
            }
            if (data[2]) {
                count |= 1;
                updateStatistics(data[2]);
            }
            if (data[3]) {
                count |= 2;
                updateGoalsRedCards(data[3], true);
            }
            if (data[4]) {
                count |= 2;
                updateGoalsRedCards(data[4], false);
            }
            if (data[5]) {
                count |= 4;
                livecourt = data[5];
            }
            if ((count & 1) == 1) {
                _drawStatistic();
            }
            if (((count & 2) == 2) || !_syn.initiated) {
                _drawTimeBar();
            }
            if ((count & 4) == 4) {
                _drawLiveCourt();
            }
            if (!_syn.initiated) {
                _syn.initiated = true;
            }
            if (redraw) {
                $M('od').onDraw();
            }
        }
    }
    this.onDrawLiveCourt = function (syncid, data) {
        _syn.rsynid = syncid;
        livecourt = data;
        _drawLiveCourt();
        $M('od').onDraw();
    }
    var statisticFile = '';
    var gHeight;
    this.onDrawLiveStatistics = function (filename, height) {
        statisticFile = filename;
        gHeight = height;
        var d = {};
        if ((_syn.mode & 2) == 2) {
            d['btn-class'] = 'ExpandBtn';
            d['status'] = 'Closed';
        } else {
            d['btn-class'] = 'CollapseBtn';
            d['status'] = '';
        }
        d['live-statistic-file'] = filename;
        d['height'] = height;
        document.getElementById('panel-live-statistics').innerHTML = _template['live-court-statistic-bsi'].getText(d);
    }
    this.onVideo = function () {
        _syn.running = false;
    }
    this.onTime = function () {
        if (_syn.running && $T('site').getValue('asi')) {
            if (_syn.refreshCount > 0) {
                _syn.refreshCount--;
            }
            if (_syn.refreshCount == 0) {
                _syn.refreshCount = _syn.refreshRate;
                var param = eventInfo[0] + ',' + (_syn.getNewStatistic ? 's,' : ',') + _syn.mode + ',' + _syn.rsynid;
                _submit('token=' + param);
            }
        }
    }
    this.onToggleCollapseExpand = function () {
        if ((_syn.mode & 2) == 0) {
            _syn.mode |= 2;
        } else if ((_syn.mode & 2) == 2) {
            _syn.mode -= 2;
        }
        if ($T('site').getValue('asi')) {
            _drawStatistic();
        } else {
            this.onDrawLiveStatistics(statisticFile, gHeight);
        }
        $M('od').onDraw();
    }
    this.loadGameState = function () {
        _updateGameState(gameState);
    }
    this.onInfoCenterClick = function () {
        var info = window.open(_infoUrl, 'livecourtinfo');
        if (info) {
            info.blur();
            info.focus();
        }
    }
    this.onBetNow = function () {
        if (eventInfo) {
            var param = eventInfo[0] + ',' + (_syn.getNewStatistic ? 's,' : ',') + _syn.mode + ',' + _syn.rsynid;
            _submit('token=' + param);
        }
    }
    this.updateEventInformation = function (data) {
        if (data) {
            if (_syn.running == false) {
                this.start(data);
                return;
            }
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                if (obj) {
                    eventInfo[i] = obj;
                }
            }
            if (gameState.length > 0 && (data[2] || data[3])) {
                _drawTimeBar();
            }
        }
    }

    function reinitialize() {
        eventInfo = [];
        gameState = [];
        goals = [];
        redCards = [];
        stats = [];
        livecourt = [];
        _target = [];
        _syn.rsynid = -1;
        _syn.initiated = false;
        _syn.getNewStatistic = false;
    }

    function updateGameState(data) {
        if (data) {
            if (data[0] != gameState[0] || data[1] != gameState[1]) {
                gameState = data;
                _updateGameState(data);
            }
        }
    }

    function updateGoalsRedCards(data, isGoalType) {
        if (data) {
            if (isGoalType) {
                goals = data;
            } else {
                redCards = data;
            }
        }
    }

    function updateStatistics(data) {
        if (data) {
            var home = data[0];
            var away = data[1];
            var c;
            if (stats[0] && stats[1]) {
                if (home) {
                    updateStatisticsCacheInfo(stats[0], home);
                }
                if (away) {
                    updateStatisticsCacheInfo(stats[1], away);
                }
            } else {
                stats = [home, away];
            }
        }
    }

    function updateStatisticsCacheInfo(c, data) {
        if (c) {
            if (data[0]) {
                c[0] = data[0];
            }
            if (data[1]) {
                c[1] = data[1];
            }
            if (data[2]) {
                c[2] = data[2];
            }
            if (data[3]) {
                c[3] = data[3];
            }
            if (data[4]) {
                c[4] = data[4];
            }
            if (data[5]) {
                c[5] = data[5];
            }
            if (data[6]) {
                c[6] = data[6];
            }
        } else {
            c = data;
        }
    }

    function getGameState() {
        return gameState.join(':');
    }

    function _updateGameState(gameState) {
        if (_target['live-court-embed']) {
            if (_target['live-court-embed'].UpdateGameState) {
                _target['live-court-embed'].UpdateGameState(gameState.join(':'));
            }
        }
    }

    function _submit(param) {
        $P.sendRequest('lc', url + '?' + param);
        param = undefined;
    }

    function _drawTimeBar() {
        if (!_target['time-bar']) {
            _target['time-bar'] = document.getElementById('panel-time-bar');
        }
        _target['time-bar'].innerHTML = _getTimeBarIcon();
    }

    function _drawStatistic() {
        if (!_target['statistics']) {
            _target['statistics'] = document.getElementById('panel-live-statistics');
        }
        _target['statistics'].innerHTML = _getStatistics();
    }

    function _drawLiveCourt() {
        if (!_target['live-court']) {
            _target['live-court'] = document.getElementById('panel-live-court');
        }
        _target['live-court'].innerHTML = _getLiveCourt();
        _target['live-court-embed'] = _getEmbedObject('livecourt');
    }
    var time_bar_icon_length = 256;

    function _getGoalsCardsIcon(type, team, minutes) {
        var gd = [];
        gd['icon-type'] = type;
        if (type == 'IconGoal') {
            gd['goal-card-title'] = _template['goal-title'].getText([]);
        } else {
            gd['goal-card-title'] = _template['red-card-title'].getText([]);
        }
        gd['home-away'] = team == 0 ? 'Top' : 'Below';
        gd['position'] = Math.floor((minutes * time_bar_icon_length) / 48 - 5);
        return _template['live-court-goal-cards'].getText(gd);
    }

    function _getFirstHalfGoalsCards() {
        if ((goals && goals.length > 0) || (redCards && redCards.length > 0)) {
            var fhd = [];
            var i = 0;
            for (i = 0; i < goals.length; i++) {
                if (goals[i][1] < 45 || (goals[i][1] >= 45 && goals[i][1] <= 50 && goals[i][2] == 1)) {
                    fhd.push(_getGoalsCardsIcon('IconGoal', goals[i][0], goals[i][1]));
                }
            }
            for (i = 0; i < redCards.length; i++) {
                if (redCards[i][1] < 45 || (redCards[i][1] >= 45 && redCards[i][1] <= 50 && redCards[i][2] == 1)) {
                    fhd.push(_getGoalsCardsIcon('IconRedCard', redCards[i][0], redCards[i][1]));
                }
            }
            return fhd.join('');
        }
        return '';
    }

    function _getFullTimeGoalsCards() {
        if ((goals && goals.length > 0) || (redCards && redCards.length > 0)) {
            var ftd = [];
            for (var i = 0; i < goals.length; i++) {
                if ((goals[i][1] > 50 && goals[i][1] <= 95) || (goals[i][1] >= 45 && goals[i][1] <= 50 && goals[i][2] == 2)) {
                    ftd.push(_getGoalsCardsIcon('IconGoal', goals[i][0], goals[i][1] - 45));
                }
            }
            for (var i = 0; i < redCards.length; i++) {
                if ((redCards[i][1] > 50 && redCards[i][1] <= 95) || (redCards[i][1] >= 45 && redCards[i][1] <= 50 && redCards[i][2] == 2)) {
                    ftd.push(_getGoalsCardsIcon('IconRedCard', redCards[i][0], redCards[i][1] - 45));
                }
            }
            return ftd.join('');
        }
        return '';
    }

    function _getTimeBarIcon() {
        var home = {
            1: {},
            2: {},
            3: {},
            4: {},
            0: {}
        };
        var away = {
            1: {},
            2: {},
            3: {},
            4: {},
            0: {}
        };
        var minute, period, currentMinute, extraMinute, total;
        var td = [];
        var eventId = livecourt[4];
        var tagEvent = null;
        var totalMinute = 45;
        var duration = null;
        if (eventId) {
            var oddModel = $P.getModel('od');
            if (oddModel && oddModel.getTagEvent) {
                tagEvent = oddModel.getTagEvent(eventId);
                if (tagEvent) {
                    var extraInfo = tagEvent[3];
                    if (extraInfo) {
                        duration = extraInfo[8];
                    }
                }
            }
        }
        if (!duration) return _template['live-court-time-bar-icon'].getText(td);
        if (gameState && _template['live-court-time-bar-icon']) {
            if ((goals && goals.length > 0) || (redCards && redCards.length > 0)) {
                var goal = null;
                var side = -1;
                for (var g = 0; g < goals.length; g++) {
                    goal = goals[g];
                    if (goal && goal.length >= 3) {
                        side = goal[0];
                        minute = goal[1];
                        period = goal[2];
                        currentMinute = minute;
                        extraMinute = '';
                        switch (period) {
                        case 1:
                            totalMinute = duration[1];
                            break;
                        case 2:
                            totalMinute = duration[1] + duration[2];
                            break;
                        case 3:
                            totalMinute = duration[1] + duration[2] + duration[3];
                            break;
                        case 4:
                            totalMinute = duration[1] + duration[2] + duration[3] + duration[4];
                            break;
                        }
                        if (minute > totalMinute) {
                            extraMinute = '+' + (minute - totalMinute) + '\'';
                            currentMinute = totalMinute;
                        }
                        if (side == 0) {
                            if (!home[period][minute]) {
                                home[period][minute] = [];
                            }
                            home[period][minute].push(_template['goal-at'].getText({
                                'minute': currentMinute,
                                'extra-minute': extraMinute
                            }));
                        } else {
                            if (!away[period][minute]) {
                                away[period][minute] = [];
                            }
                            away[period][minute].push(_template['goal-at'].getText({
                                'minute': currentMinute,
                                'extra-minute': extraMinute
                            }));
                        }
                    }
                }
                var redCard = null;
                for (var r = 0; r < redCards.length; r++) {
                    redCard = redCards[r];
                    if (redCard && redCard.length >= 3) {
                        side = redCard[0];
                        minute = redCard[1];
                        period = redCard[2];
                        currentMinute = minute;
                        extraMinute = '';
                        switch (period) {
                        case 1:
                            totalMinute = duration[1];
                            break;
                        case 2:
                            totalMinute = duration[1] + duration[2];
                            break;
                        case 3:
                            totalMinute = duration[1] + duration[2] + duration[3];
                            break;
                        case 4:
                            totalMinute = duration[1] + duration[2] + duration[3] + duration[4];
                            break;
                        }
                        if (minute > totalMinute) {
                            extraMinute = '+' + (minute - totalMinute) + '\'';
                            currentMinute = totalMinute;
                        }
                        if (side == 0) {
                            if (!home[period][minute]) {
                                home[period][minute] = [];
                            }
                            home[period][minute].push(_template['red-card-at'].getText({
                                'minute': currentMinute,
                                'extra-minute': extraMinute
                            }));
                        } else {
                            if (!away[period][minute]) {
                                away[period][minute] = [];
                            }
                            away[period][minute].push(_template['red-card-at'].getText({
                                'minute': currentMinute,
                                'extra-minute': extraMinute
                            }));
                        }
                    }
                }
            }
            var homeString = [];
            var awayString = [];
            for (var i = 1; i <= 4; i++) {
                for (var minute in home[i]) homeString.push(home[i][minute].join(''));
                for (var minute in away[i]) awayString.push(away[i][minute].join(''));
            }
            td['first-half-goal-red-card'] = homeString.join('');
            td['seconf-half-goal-red-card'] = awayString.join('');
            return _template['live-court-time-bar-icon'].getText(td);
        }
        return '';
    }

    function _getFirstHalfGoalsCardsIcon() {
        if ((goals && goals.length > 0) || (redCards && redCards.length > 0)) {
            var fhd = [];
            var i = 0;
            for (i = 0; i < goals.length; i++) {
                if (goals[i][1] < 45 || (goals[i][1] >= 45 && goals[i][1] <= 50 && goals[i][2] == 1)) {
                    fhd.push(_getGoalsCardsIcon('IconGoal', goals[i][0], goals[i][1]));
                }
            }
            for (i = 0; i < redCards.length; i++) {
                if (redCards[i][1] < 45 || (redCards[i][1] >= 45 && redCards[i][1] <= 50 && redCards[i][2] == 1)) {
                    fhd.push(_getGoalsCardsIcon('IconRedCard', redCards[i][0], redCards[i][1]));
                }
            }
            return fhd.join('');
        }
        return '';
    }

    function _getTimeBar() {
        var time_bar_width = 270;
        if (gameState) {
            var td = [];
            td['home-team-hdp'] = eventInfo[1] && eventInfo[1] == 1 ? "Red" : "Blue";
            td['away-team-hdp'] = eventInfo[1] && eventInfo[1] == 2 ? "Red" : "Blue";
            td['fh-goals'] = _getFirstHalfGoalsCards();
            td['ft-goals'] = _getFullTimeGoalsCards();
            if (eventInfo[2] === 5) {
                td['fh-width'] = time_bar_width;
                td['ft-width'] = 0;
            } else {
                if (eventInfo[2] === 1) {
                    td['fh-width'] = Math.floor((parseInt(eventInfo[3]) / 50) * time_bar_width);
                    td['ft-width'] = 0;
                } else if (eventInfo[2] === 2) {
                    td['fh-width'] = time_bar_width;
                    td['ft-width'] = Math.floor(((parseInt(eventInfo[3]) - 45) / 50) * time_bar_width);
                }
                if (td['fh-width'] > time_bar_width) {
                    td['fh-width'] = time_bar_width;
                }
                if (td['ft-width'] > time_bar_width) {
                    td['ft-width'] = time_bar_width;
                }
            }
            return _template['live-court-time-bar'].getText(td);
        }
        return '';
    }

    function _getStatistics() {
        if (stats && stats.length == 2 && stats[0] && stats[0].length > 0 && stats[1] && stats[1].length > 0) {
            if (stats[0] && stats[1]) {
                var hd = stats[0];
                var ad = stats[1];
                var sd = [];
                if (hd[0] != undefined && ad[0] != undefined) {
                    sd.push(_getStatisticsElement(_translation['shots-text'], hd[0], ad[0]));
                }
                if (hd[1] != undefined && ad[1] != undefined) {
                    sd.push(_getStatisticsElement(_translation['ontarget-text'], hd[1], ad[1]));
                }
                if (hd[2] != undefined && ad[2] != undefined) {
                    sd.push(_getStatisticsElement(_translation['offtarget-text'], hd[2], ad[2]));
                }
                if (hd[3] != undefined && ad[3] != undefined) {
                    sd.push(_getStatisticsElement(_translation['woodwork-text'], hd[3], ad[3]));
                }
                if (hd[4] != undefined && ad[4] != undefined) {
                    sd.push(_getStatisticsElement(_translation['blocked-text'], hd[4], ad[4]));
                }
                if (hd[5] != undefined && ad[5] != undefined) {
                    sd.push(_getStatisticsElement(_translation['attack-text'], hd[5], ad[5]));
                }
                if (hd[6] != undefined && ad[6] != undefined) {
                    sd.push(_getStatisticsElement(_translation['dangerous-attack-text'], hd[6], ad[6]));
                }
                var d = [];
                d['elements'] = sd.join('');
                if ((_syn.mode & 2) == 2) {
                    d['btn-class'] = 'ExpandBtn';
                    d['status'] = 'Closed';
                } else {
                    d['btn-class'] = 'CollapseBtn';
                    d['status'] = '';
                }
                return _template['live-court-statistic'].getText(d);
            }
        }
        return '';
    }

    function _getStatisticsElement(en, hv, av) {
        var sd = [];
        if (hv < 0) hv = 0;
        if (av < 0) av = 0;
        var minLengthPerc = '7';
        sd['live-court-stats-element'] = en;
        sd['home-value'] = hv;
        sd['home-perc'] = (hv == 0) ? minLengthPerc : (Math.ceil((hv * 100) / (hv + av)) < minLengthPerc ? minLengthPerc : Math.ceil((hv * 100) / (hv + av)));
        sd['away-value'] = av;
        sd['away-perc'] = (av == 0) ? minLengthPerc : (Math.ceil((av * 100) / (hv + av)) < minLengthPerc ? minLengthPerc : Math.ceil((av * 100) / (hv + av)));
        return _template['live-court-statistic-value'].getText(sd);
    }

    function _getLiveCourt() {
        var d = {};
        d['flash-vars'] = livecourt[0];
        d['version'] = livecourt[1];
        d['live-court-file'] = livecourt[2];
        d['height'] = livecourt[3];
        return _template['live-court-player'].getText(d);
    }

    function _getEmbedObject(name) {
        return document[name];
    }
}

function onInfoCenterClick() {
    $M('lc').onInfoCenterClick();
}

function __EuroModelLiveStreaming() {
    var _self = this;
    var _template = tilib_GenerateTemplates($P.getTemplate('ls'));
    var _cache = new __EuroCacheStreaming();
    this.onUpdate = function (data) {
        if (_cache.update(data)) {
            _draw();
        }
        updateStreamingVideoPeriod();
    };
    this.onClear = function () {
        p = document.getElementById('panel-live-streaming');
        if (p) {
            p.style.display = 'none';
            p.innerHTML = '';
        }
        _cache.clear();
    };
    this.onSBOBETvClick = function () {
        var video = _cache.getVideo();
        if (video && video[0]) {
            $M('od').onLiveTV(video[0]);
        }
    };
    this.getState = function () {
        var pid = $T('od').getValue('pid');
        if (pid == 25) {
            var video = _cache.getVideo();
            if (video) {
                return video[1];
            }
        }
        return 0;
    };
    this.getStreamingVideoInfo = function () {
        if (_cache) {
            return _cache.getVideo();
        } else {
            return null;
        }
    }

    function updateStreamingVideoPeriod() {
        if (_cache) {
            var video = _cache.getVideo();
            if (video[3]) {
                UpdateEventPeriod(video[3]);
            }
        }
    }

    function _draw() {
        var video = _cache.getVideo();
        var template = null;
        var d = {};
        if (video) {
            d['flash-vars'] = video[2];
            switch (video[1]) {
            case 1:
                template = _template['flash-object-stream'];
                break;
            case 2:
                template = _template['flash-object-demo'];
                break;
            case 5:
                template = _template['flash-object-trial-watching'];
                break;
            case 6:
                template = _template['flash-object-trial-watched'];
                break;
            }
            content = (template) ? template.getText(d) : null;
        }
        var e = document.getElementById('panel-live-streaming');
        if (e && template) {
            e.innerHTML = template.getText(d);
            e.style.display = 'block';
        } else {
            e.innerHTML = '';
            e.style.display = 'none';
        }
    }
}

function onPopupSBOBETv() {
    $M('ls').onSBOBETvClick();
}

function onBetNowClick() {
    $M('od').onRefresh();
}

function __EuroModelHighlight(refreshRate) {
    var _template = tilib_GenerateTemplates($P.getTemplate('hl'));
    var _cache = [];
    var _selTmpl;
    var _hasPriceChange = false;
    var _isFirstInit = false;
    var _syn = {
        cooldownCount: 0,
        refreshRate: refreshRate,
        running: false
    };

    function _getUrl(action) {
        var sb = [];
        sb.push('/');
        sb.push($T('site').getValue('lang'));
        sb.push('/data/highlight');
        sb.push('?act=');
        sb.push(action);
        sb.push('&tk=');
        sb.push($T('od').getToken());
        return sb.join('');
    }
    this.start = function () {
        _cache = [];
        _syn.running = true;
        _syn.cooldownCount = 0;
        _isFirstInit = true;
        var sid = $T('od').getValue('sid');
        var pid = $T('od').getValue('pid');
        if (pid == 2) {
            $P.sendRequest('hl', _getUrl('gi'));
        } else if (pid == 40) {
            $P.sendRequest('hl', _getUrl('cs&sid=25'));
        } else {
            if (sid && sid > 0) {
                $P.sendRequest('hl', _getUrl('cs&sid=' + sid));
            } else {
                $P.sendRequest('hl', _getUrl('gi'));
            }
        }
    }
    this.stop = function () {
        _syn.running = false;
        _syn.cooldownCount = 0;
        var h = document.getElementById("panel-highlight");
        if (h) {
            h.style.display = 'none';
            h.innerHTML = '';
        }
    }
    this.onClick = function (event) {
        if (!event) event = window.event;
        if (!_onClick(event)) {
            event.returnValue = false;
            return false;
        }
        return true;
    };

    function _onClick(event) {
        var e = event.srcElement ? event.srcElement : event.target;
        while (e) {
            var id = e.id;
            e = e.parentNode;
            if (!id) continue;
            var atom = id.split(':');
            var count = atom.length;
            if (count >= 3 && atom[0] == 'bu' && atom[1] == 'hl') {
                switch (atom[2]) {
                case 'go':
                    if (count >= 4) {
                        switch (atom[3]) {
                        case 'ev':
                            if (count >= 5) {
                                return !_goEvent(atom[4]);
                            }
                            break;
                        case 'to':
                            if (count >= 5) {
                                return $M('euro').goTournament(atom[4]);
                            }
                            break;
                        case 'sp':
                            if (count >= 5) {
                                return $M('euro').goSport(atom[4]);
                            }
                            break;
                        case 'or':
                            if (count >= 5) {
                                var orData = $E('tournaments')[atom[4]];
                                if (!_cache || _cache.length == 0) {
                                    return true;
                                }
                                if (orData) {
                                    return !$M('euro').goOutright(orData[2], orData[3], atom[5], atom[4]);
                                }
                                return !$M('euro').goTournament(atom[4]);
                            }
                            break;
                        }
                    }
                }
            }
        }
        return true;
    }

    function _goEvent(eid) {
        if (!eid || eid == 0 || !_cache || _cache.length == 0) {
            return false;
        }
        var lid = 0;
        var home = '';
        var away = '';
        var count = _cache.length;
        var evt;
        var oddsInfo;
        for (var i = 0; i < count; i++) {
            if (!_cache[i] || !_cache[i][0]) {
                continue;
            }
            evt = _cache[i][0];
            if (evt && evt['eid'] == eid && evt['lid']) {
                lid = evt['lid'];
                if (evt['oi']) {
                    oddsInfo = evt['oi'];
                    if (oddsInfo && oddsInfo['away'] && oddsInfo['home']) {
                        home = oddsInfo['home'];
                        away = oddsInfo['away'];
                        break;
                    }
                }
            }
        }
        if (lid && home && away) {
            $M('od').goFavEvent(lid, eid, home, away);
            return true;
        }
        return false;
    }
    this.onSportChange = function (sid) {
        _cache = [];
        $P.sendRequest('hl', _getUrl('cs&sid=' + sid));
    }
    this.onTime = function () {
        if (!_syn.running) {
            return;
        }
        if (_syn.cooldownCount != 0) {
            _syn.cooldownCount--;
            return;
        }
        if (_cache != null && _cache.length > 0) {
            var vc = [];
            for (var i = 0; i < _cache.length; i++) {
                if (_cache[i] == undefined || _cache[i][0] == undefined) {
                    continue;
                }
                var item = _cache[i][0];
                if (item && item['oi'] && item['mkt']) {
                    if (item['mkt'] > 2) {
                        var ovc = [];
                        for (var a = 0; a < item['mkt'] - 1; a++) {
                            var oitem = item['oi'][a];
                            if (oitem && oitem['oid']) {
                                ovc[ovc.length] = oitem['oid'] + ':' + oitem['ovc'] + ';';
                            }
                        }
                        vc[vc.length] = ovc.join('');
                    } else {
                        if (item['oi']['oid'] != undefined && item['oi']['ovc'] != undefined) {
                            vc[vc.length] = item['oi']['oid'] + ':' + item['oi']['ovc'] + ';';
                        }
                    }
                }
            }
            var sid = $T('od').getValue('sid');
            $P.sendRequest('hl', _getUrl('uo&sid=' + sid + '&ovc=' + vc.join('')));
            _syn.cooldownCount = _syn.refreshRate;
        }
    }
    this.onChangeTemplate = function (data, sid) {
        var template = tilib_GenerateTemplates($P.getTemplate('hl-' + sid));
        _selTmpl = template['hl-' + sid];
        this.onUpdate(data);
    }
    this.onOptionSelected = function (tid, key, selected) {
        var p = document.getElementById('hl-' + tid + '-' + key);
        var cp = document.getElementById('hl-' + tid + '-' + key + '_tmpl');
        if (selected) {
            if (p) {
                p.className = p.className + ' OddsSel';
            }
            if (cp) {
                cp.className = cp.className + ' OddsSel';
            }
        } else {
            if (p) {
                p.className = p.className.replace(/OddsSel/gi, '');
            }
            if (cp) {
                cp.className = cp.className.replace(/OddsSel/gi, '');
            }
        }
        _nox_highlights.reload(false);
    };
    this.onPrice = function (mid, oid, opindex, price) {
        if (mid && oid && opindex && price) {
            var m = $M('od');
            if (m && m.onPrice) {
                m.onPrice(mid, oid, opindex, price);
            }
        }
    }
    this.onPriceChange = function (data) {
        if (data) {
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                if (item[0] && item[0] == 39 && item[1] && item[2] && item[2][0] && item[2][2]) {
                    _UpdatePrice(item[2][0], item[2][2], item[1], null, true);
                    _hasPriceChange = true;
                }
                var oddsInfo = item[4];
                if (oddsInfo) {
                    var ovc = oddsInfo[0];
                    var oid = oddsInfo[1][0];
                    var obase = oddsInfo[1][1];
                    var price = oddsInfo[1][2];
                    _UpdatePrice(oid, price, ovc, obase, false);
                    _hasPriceChange = true;
                }
            }
        }
    }

    function _UpdatePrice(oddsid, price, version, obase, isOutright) {
        if (!oddsid && !price) {
            return;
        }
        if (_cache != null && _cache.length > 0) {
            for (var i = 0; i < _cache.length; i++) {
                if (!_cache[i] && _cache[i][0] == undefined) {
                    continue;
                }
                var item = _cache[i][0];
                if (item['oi'] && ((item['oi']['oid'] != undefined && item['oi']['oid'] == oddsid) || isOutright)) {
                    if (!isOutright) {
                        if (item['mkt']) {
                            if (item['mkt'] == 1) {
                                if (price != undefined) {
                                    if (price[0]) {
                                        if (price[0] > item['oi']['price1']) {
                                            item['oi']['price1c'] = 1;
                                        }
                                        if (price[0] < item['oi']['price1']) {
                                            item['oi']['price1c'] = -1;
                                        }
                                        item['oi']['price1'] = price[0];
                                    }
                                    if (price[1]) {
                                        if (price[1] > item['oi']['pricex']) {
                                            item['oi']['pricexc'] = 1;
                                        }
                                        if (price[1] < item['oi']['pricex']) {
                                            item['oi']['pricexc'] = -1;
                                        }
                                        item['oi']['pricex'] = price[1];
                                    }
                                    if (price[2]) {
                                        if (price[2] > item['oi']['price2']) {
                                            item['oi']['price2c'] = 1;
                                        }
                                        if (price[2] < item['oi']['price2']) {
                                            item['oi']['price2c'] = -1;
                                        }
                                        item['oi']['price2'] = price[2];
                                    }
                                }
                            }
                            if (item['mkt'] == 2) {
                                if (price != undefined) {
                                    if (price[0]) {
                                        if (price[0] > item['oi']['hprice']) {
                                            item['oi']['hpricec'] = 1;
                                        }
                                        if (price[0] < item['oi']['hprice']) {
                                            item['oi']['hpricec'] = -1;
                                        }
                                        item['oi']['hprice'] = price[0];
                                    }
                                    if (price[1]) {
                                        if (price[1] > item['oi']['aprice']) {
                                            item['oi']['apricec'] = 1;
                                        }
                                        if (price[1] < item['oi']['aprice']) {
                                            item['oi']['apricec'] = -1;
                                        }
                                        item['oi']['aprice'] = price[1];
                                    }
                                }
                                if (obase) {
                                    if (obase[3]) {
                                        item['oi']['point'] = obase[3];
                                    }
                                }
                            }
                            item['oi']['ovc'] = version;
                        }
                    }
                    if (item['mkt'] > 2) {
                        var max = item['mkt'] - 1;
                        if (!item['oi']) {
                            continue;
                        }
                        for (var a = 0; a < max; a++) {
                            if (!item['oi'][a]) {
                                continue;
                            }
                            if (item['oi'][a]['oid'] == oddsid) {
                                if (price > item['oi'][a]['price']) {
                                    item['oi'][a]['pc'] = 1;
                                }
                                if (price < item['oi'][a]['price']) {
                                    item['oi'][a]['pc'] = -1;
                                }
                                item['oi'][a]['price'] = price;
                                item['oi'][a]['ovc'] = version;
                            }
                        }
                    }
                    item['oi']['ovc'] = version;
                    _cache[i][0] = item;
                }
            }
            $M('hl').onUpdate(_cache);
        }
    }
    this.onIdle = function () {
        if (_hasPriceChange) {
            $M('hl').onUpdate(_cache);
            _hasPriceChange = false;
        }
    }
    this.onUpdate = function (dat) {
        var i = 1;
        if (_selTmpl == undefined) {
            _selTmpl = _template['hl-0'];
        }
        if (_cache.length == 0 && dat) {
            _cache = dat;
        }
        var d = [];
        var data = dat;
        for (i = 0; i < 5; i++) {
            if (data) {
                if (data[i]) {
                    var aData = data[i][0];
                    if (aData == undefined) {
                        continue;
                    }
                    if (aData['mkt']) {
                        if (aData['mkt'] == 1) {
                            d = _assign1x2Data(i, aData, d);
                        }
                        if (aData['mkt'] == 2) {
                            d = _assignHDPData(i, aData, d);
                        }
                        if (aData['mkt'] > 2) {
                            d = _assignOutrightData(i, aData, d);
                        }
                    }
                    if (!($T('site').getValue('seo') || history.pushState)) {
                        d['href' + aData['up']] = $M('euro').getEuroUrlBase() + '#!/' + aData['url'];
                    } else {
                        d['href' + aData['up']] = $M('euro').getEuroUrlBase() + aData['url'];
                    }
                    if (aData['at']) {
                        switch (aData['at']) {
                        case 'em':
                            d['id' + aData['up'] + ':0'] = '';
                            d['id' + aData['up'] + ':1'] = '';
                            break;
                        case 'sp':
                            d['id' + aData['up'] + ':0'] = 'bu:hl:go:sp:' + aData['sid'];
                            d['id' + aData['up'] + ':1'] = 'bu:hl:go:sp:' + aData['sid'];
                            break;
                        case 'to':
                            d['id' + aData['up'] + ':0'] = 'bu:hl:go:to:' + aData['lid'];
                            d['id' + aData['up'] + ':1'] = 'bu:hl:go:to:' + aData['lid'];
                            break;
                        case 'ev':
                            d['id' + aData['up'] + ':0'] = 'bu:hl:go:ev:' + aData['eid'];
                            d['id' + aData['up'] + ':1'] = 'bu:hl:go:ev:' + aData['eid'];
                            break;
                        case 'or':
                            d['id' + aData['up'] + ':0'] = 'bu:hl:go:or:' + aData['lid'] + ':' + aData['dt'];
                            d['id' + aData['up'] + ':1'] = 'bu:hl:go:or:' + aData['lid'] + ':' + aData['dt'];
                            break;
                        }
                    }
                }
            }
        }
        var h = document.getElementById("panel-highlight");
        if (h && _selTmpl) {
            h.style.display = 'block';
            h.innerHTML = _selTmpl.getText(d);
            if (_isFirstInit) {
                _nox_highlights.init();
                _isFirstInit = false;
            } else {
                _nox_highlights.reload(false);
                _nox_highlights.displayData(_nox_highlights.idx);
                _nox_highlights.selectedImage();
            }
        }
    }

    function _assignHDPData(position, data, container) {
        var bi = data['oi'];
        var d = container;
        if (!bi) {
            return container;
        }
        var d = container;
        var hprice = bi['hprice'];
        var aprice = bi['aprice'];
        d['home-' + position] = bi['home'];
        d['price-' + position + '-h'] = tilib_GetPriceString(hprice);
        d['point-' + position + '-h'] = _getHdp1(bi['point']);
        d['away-' + position] = bi['away'];
        d['price-' + position + '-a'] = tilib_GetPriceString(aprice);
        d['point-' + position + '-a'] = _getHdp2(bi['point']);
        d['href-price-' + position + '-h'] = _getOnPriceLink('s', bi['oid'], 'h', hprice);
        d['href-price-' + position + '-a'] = _getOnPriceLink('s', bi['oid'], 'a', aprice);
        d['id-price-' + position + '-h'] = 'hl-s-' + bi['oid'] + '-h';
        d['id-price-' + position + '-a'] = 'hl-s-' + bi['oid'] + '-a';
        if (!hprice || hprice == 0) {
            d['class-price-' + position + '-h'] = 'OddsHidden';
            d['price-' + position + '-h'] = '';
        } else {
            d['class-price-' + position + '-h'] = 'OddsTabL';
        }
        if (!aprice || aprice == 0) {
            d['class-price-' + position + '-a'] = 'OddsHidden';
            d['price-' + position + '-a'] = '';
        } else {
            d['class-price-' + position + '-a'] = 'OddsTabL';
        }
        if (bi['hpricec']) {
            if (bi['hpricec'] > 0) {
                d['class-price-' + position + '-h'] += ' PriceUp';
            } else {
                d['class-price-' + position + '-h'] += ' PriceDown';
            }
            bi['hpricec'] = null;
        }
        if (bi['apricec']) {
            if (bi['apricec'] > 0) {
                d['class-price-' + position + '-a'] += ' PriceUp';
            } else {
                d['class-price-' + position + '-a'] += ' PriceDown';
            }
            bi['apricec'] = null;
        }
        if ($M('bs').isOptionSelected('s', bi['oid'], 'h')) {
            d['class-price-' + position + '-h'] += ' OddsSel';
        }
        if ($M('bs').isOptionSelected('s', bi['oid'], 'a')) {
            d['class-price-' + position + '-a'] += ' OddsSel';
        }
        return d;
    }

    function _assign1x2Data(position, data, container) {
        var bi = data['oi'];
        var d = container;
        if (!bi) {
            return container;
        }
        var price1 = bi['price1'];
        var pricex = bi['pricex'];
        var price2 = bi['price2'];
        d['home-' + position] = bi['home'];
        d['draw-' + position] = bi['draw'];
        d['away-' + position] = bi['away'];
        d['price-' + position + '-1'] = tilib_GetPriceString(price1);
        d['price-' + position + '-x'] = tilib_GetPriceString(pricex);
        d['price-' + position + '-2'] = tilib_GetPriceString(price2);
        d['href-price-' + position + '-1'] = _getOnPriceLink('s', bi['oid'], '1', price1);
        d['href-price-' + position + '-x'] = _getOnPriceLink('s', bi['oid'], 'x', pricex);
        d['href-price-' + position + '-2'] = _getOnPriceLink('s', bi['oid'], '2', price2);
        d['id-price-' + position + '-1'] = 'hl-s-' + bi['oid'] + '-1';
        d['id-price-' + position + '-x'] = 'hl-s-' + bi['oid'] + '-x';
        d['id-price-' + position + '-2'] = 'hl-s-' + bi['oid'] + '-2';
        if (!price1 || price1 <= 0) {
            d['class-price-' + position + '-1'] = 'OddsHidden';
            d['price-' + position + '-1'] = '';
        } else {
            d['class-price-' + position + '-1'] = 'OddsTabL';
        }
        if (bi['price1c']) {
            if (bi['price1c'] > 0) {
                d['class-price-' + position + '-1'] += ' PriceUp';
            } else {
                d['class-price-' + position + '-1'] += ' PriceDown';
            }
            bi['price1c'] = null;
        }
        if (!pricex || pricex <= 0) {
            d['class-price-' + position + '-x'] = 'OddsHidden';
            d['price-' + position + '-x'] = '';
        } else {
            d['class-price-' + position + '-x'] = 'OddsTabL';
        }
        if (bi['pricexc']) {
            if (bi['pricexc'] > 0) {
                d['class-price-' + position + '-x'] += ' PriceUp';
            } else {
                d['class-price-' + position + '-x'] += ' PriceDown';
            }
            bi['pricexc'] = null;
        }
        if (!price2 || price2 <= 0) {
            d['class-price-' + position + '-2'] = 'OddsHidden';
            d['price-' + position + '-2'] = '';
        } else {
            d['class-price-' + position + '-2'] = 'OddsTabL';
        }
        if (bi['price2c']) {
            if (bi['price2c'] > 0) {
                d['class-price-' + position + '-2'] += ' PriceUp';
            } else {
                d['class-price-' + position + '-2'] += ' PriceDown';
            }
            bi['price2c'] = null;
        }
        if ($M('bs').isOptionSelected('s', bi['oid'], '1')) {
            d['class-price-' + position + '-1'] += ' OddsSel';
        }
        if ($M('bs').isOptionSelected('s', bi['oid'], 'x')) {
            d['class-price-' + position + '-x'] += ' OddsSel';
        }
        if ($M('bs').isOptionSelected('s', bi['oid'], '2')) {
            d['class-price-' + position + '-2'] += ' OddsSel';
        }
        return d;
    }

    function _assignOutrightData(position, data, container) {
        var bi = data['oi'];
        var d = container;
        if (!bi || bi == undefined) {
            return container;
        }
        bi.sort(_SortByPrice);
        var max = data['mkt'] - 1;
        var i = 0;
        var r = 1;
        var key = '';
        var price = 0;
        for (i = 0; i < max; i++) {
            d['class-price-' + position + '-' + r] = 'OddsTabL';
            if (bi && bi[i] != undefined) {
                d['team-' + position + '-' + r] = bi[i]['team'];
                price = bi[i]['price'];
                if (price <= 0) {
                    d['class-price-' + position + '-' + r] = 'OddsHidden';
                }
                d['price-' + position + '-' + r] = tilib_GetPriceString(price);
                d['id-price-' + position + '-' + r] = 'hl-o-' + bi[i]['oid'] + '-0';
                d['href-price-' + position + '-' + r] = _getOnPriceLink('o', bi[i]['oid'], '0', price);
                if (bi[i]['pc']) {
                    if (bi[i]['pc'] > 0) {
                        d['class-price-' + position + '-' + r] += ' PriceUp';
                    } else {
                        d['class-price-' + position + '-' + r] += ' PriceDown';
                    }
                    bi[i]['pc'] = null;
                }
                if (bi[i]['oid'] && $M('bs') && $M('bs').isOptionSelected('o', bi[i]['oid'], '0')) {
                    d['class-price-' + position + '-' + r] += ' OddsSel';
                }
            } else {
                d['team-' + position + '-' + r] = '';
                d['price-' + position + '-' + r] = '';
                d['href-price-' + position + '-' + r] = '';
                d['class-price-' + position + '-' + r] = 'OddsHidden';
            }
            r++;
        }
        return d;
    }

    function _getOnPriceLink(tkt, oid, optidx, price) {
        var d = [];
        d['tkt'] = tkt;
        d['oid'] = oid;
        d['opt-idx'] = optidx;
        d['price'] = price;
        return _template['hl-price'].getText(d);
    }

    function _SortByPrice(item1, item2) {
        if (item1 && item2) {
            var d1 = item1['price'];
            var d2 = item2['price'];
            return d2 < d1;
        }
    }

    function _getHdp1(point) {
        if (point) {
            var p = parseFloat(point);
            if (p == 0) {
                return '0.00';
            }
            if (p > 0) {
                return '-' + p.toFixed(2);
            } else {
                return '+' + -p.toFixed(2);
            }
        }
        return '0.00';
    }

    function _getHdp2(point) {
        if (point) {
            var p = parseFloat(point);
            if (p == 0) {
                return '0.00';
            }
            if (p < 0) {
                return '-' + -p.toFixed(2);
            } else {
                return '+' + p.toFixed(2);
            }
        }
        return '0.00';
    }
}
var bs_euroOddsMkt = {
    1: 0,
    2: 0,
    3: 0,
    4: 1,
    5: 1,
    6: 1,
    7: 0,
    8: 1,
    9: 0,
    10: 1,
    11: 1,
    12: 0,
    13: 1,
    14: 1,
    15: 1,
    16: 1,
    17: 1,
    39: 1
}
var bs_euroOddsMktWithPoint = {
    1: 1,
    2: 0,
    3: 1,
    4: 0,
    5: 0,
    6: 0,
    7: 1,
    8: 0,
    9: 1,
    10: 0,
    11: 0,
    12: 0,
    13: 0,
    14: 0,
    15: 0,
    16: 0,
    17: 0,
    39: 0
}

    function bs_EuroModel(url, orderUrl, currency) {
        var _translation = $P.getTranslation('bs');
        var _oe = $E('odds-option');
        var _url = url;
        var _elemTranslation = $E('translation');
        var _orderUrl = orderUrl;
        var _template = tilib_GenerateTemplates($P.getTemplate('bs'));
        var _orderedIds = [];
        var _sCachedBetSlip = {};
        var _mpData = [];
        var _mid = [];
        var _mpCachedBetSlip = {};
        var _orCachedBetSlip = {};
        var _target = [];
        var _acceptBetterOdds = false;
        var _syn = {
            currency: currency,
            bc: 0,
            displayState: 0,
            allSoccer: 100000,
            nonAllSoccer: 20000,
            eachBet: 0
        };
        var _receiptContent = '';
        var _isOddsClosed = false;
        var _gmtHKTimeZone = ' GMT +8';
        var lastSuccessStake;
        var _fcCurrentFCKey = '';
        var _fcAllFCStake = {};

        function _generateBet(data) {
            if (data) {
                var d = [];
                d.push(data[0]);
                d.push(data[9]);
                d.push(data[14] ? "1" : "0");
                d.push(data[7]);
                d.push(data[20]);
                return 's:' + d.join('_');
            }
            return '';
        }

        function _generateMPBet(data) {
            if (data) {
                var d = [];
                d.push(data[0]);
                d.push(data[9]);
                d.push(data[7]);
                return d.join('_');
            }
            return '';
        }

        function _generateORBet(data) {
            if (data) {
                var d = [];
                d.push(data[0]);
                d.push(data[6] ? "1" : "0");
                d.push(data[7] ? "1" : "0");
                d.push(data[4]);
                d.push(data[12]);
                return 'o:' + d.join('_');
            }
            return '';
        }

        function _computeFooter() {
            var tstake = 0;
            var twin = 0;
            var es = _getObjectWithId('tstake');
            var ew = _getObjectWithId('twin');
            if (ew && es) {
                if (_orderedIds) {
                    for (var i = 0; i < _orderedIds.length; i++) {
                        var d = _orderedIds[i];
                        if (d) {
                            var obj;
                            var stakeValue;
                            var winValue;
                            switch (d[0]) {
                            case 's':
                                if (_sCachedBetSlip) {
                                    obj = _sCachedBetSlip[d[1]];
                                    if (obj && obj[14]) {
                                        stakeValue = obj[20];
                                        winValue = obj[21];
                                        tstake += isNaN(stakeValue) ? 0 : parseFloat(stakeValue);
                                        twin += isNaN(winValue) ? 0 : parseFloat(winValue);
                                        twin = tilib_CorrectFloat(twin);
                                    }
                                }
                                break;
                            case 'm':
                                if (_mpCachedBetSlip) {
                                    if (_mpData && _mpData[1]) {
                                        stakeValue = _mpData[5];
                                        winValue = _mpData[6];
                                        tstake += isNaN(stakeValue) ? 0 : parseFloat(stakeValue);
                                        twin += isNaN(winValue) ? 0 : parseFloat(winValue);
                                        twin = tilib_CorrectFloat(twin);
                                    }
                                }
                                break;
                            case 'o':
                                if (_orCachedBetSlip) {
                                    obj = _orCachedBetSlip[d[1]];
                                    if (obj && obj[7]) {
                                        stakeValue = obj[12];
                                        winValue = obj[13];
                                        tstake += isNaN(stakeValue) ? 0 : parseFloat(stakeValue);
                                        twin += isNaN(winValue) ? 0 : parseFloat(winValue);
                                        twin = tilib_CorrectFloat(twin);
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                _reCalculateMPOdds();
                if (!isNaN(tstake) && !isNaN(twin)) {
                    es.innerHTML = _syn.currency + ' ' + _addCommas(tilib_RoundDown(tstake, 3));
                    twin = tilib_RoundDown(twin + tstake, 2).toFixed(2);
                    ew.innerHTML = _syn.currency + ' ' + _addCommas(twin);
                } else {
                    es.innerHTML = _syn.currency + ' 0.00';
                    ew.innerHTML = _syn.currency + ' 0.00';
                }
            }
        }

        function _submit(url, param) {
            if (param) {
                param += '&uid=' + $T('site').getValue('uid');
            } else {
                param = '?uid=' + $T('site').getValue('uid');
            }
            $P.sendRequest('bs', url + param);
            param = undefined;
        }

        function _updateDataIntoCache(data) {
            if (data) {
                for (var i = 0; i < data.length; i++) {
                    var dataArr = data[i];
                    if (dataArr) {
                        var type = dataArr[0];
                        var objArr = dataArr[1];
                        for (var si = 0; si < objArr.length; si++) {
                            var obj = objArr[si];
                            if (obj) {
                                switch (type) {
                                case 's':
                                    _updateSingleMPData(type, obj);
                                    break;
                                case 'm':
                                    _updateSingleMPData(type, obj);
                                    break;
                                case 'o':
                                    _updateOutrightData(obj);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        function _updateDeletedDataIntoCache(data) {
            if (data) {
                for (var i = 0; i < data.length; i++) {
                    var dataArr = data[i];
                    if (dataArr) {
                        var type = dataArr[0];
                        var objArr = dataArr[1];
                        for (var si = 0; si < objArr.length; si++) {
                            var obj = objArr[si];
                            if (obj) {
                                switch (type) {
                                case 's':
                                    if (_sCachedBetSlip) {
                                        cd = _sCachedBetSlip[obj[0]];
                                        if (cd) {
                                            cd[19] = 2;
                                        }
                                    }
                                    break;
                                case 'm':
                                    if (_mpCachedBetSlip) {
                                        cd = _mpCachedBetSlip[obj[0]];
                                        if (cd) {
                                            cd[19] = 2;
                                            _mpData[0] = tilib_CorrectFloat(_mpData[0] / cd[7]);
                                        }
                                    }
                                    break;
                                case 'o':
                                    if (_orCachedBetSlip) {
                                        cd = _orCachedBetSlip[obj[0]];
                                        if (cd) {
                                            cd[11] = 2;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        function _reCalculateMPOdds() {
            if (_mpCachedBetSlip) {
                var mp;
                _mpData[0] = 1;
                for (var key in _mpCachedBetSlip) {
                    mp = _mpCachedBetSlip[key];
                    if (mp) {
                        _mpData[0] = tilib_CorrectFloat(_mpData[0] * mp[7]);
                    }
                }
            }
        }

        function _updateSingleMPData(type, data) {
            if (data) {
                var key = data[0] + '-' + data[1];
                var cd = type == 's' ? _sCachedBetSlip[key] : _mpCachedBetSlip[key];
                if (cd) {
                    if (data[2]) {
                        cd[5] = data[2];
                    }
                    if (data[3]) {
                        cd[6] = data[3];
                    }
                    if (data[4]) {
                        cd[3] = data[4];
                    }
                    if (data[5]) {
                        cd[16] = cd[7];
                        cd[7] = data[5];
                    }
                    if (data[6]) {
                        cd[10] = data[6];
                    }
                    if (data[7]) {
                        cd[12] = data[7];
                    }
                    if (data[8]) {
                        cd[13] = data[8];
                    }
                    if (cd[19] == 2) {
                        cd[19] = 0;
                    }
                    if (data[9] != undefined && data[9] != null) {
                        cd[24] = data[9];
                    }
                    cd[25] = data[10];
                }
            }
        }

        function _updateOutrightData(data) {
            if (data) {
                var key = data[0] + '-' + data[1];
                var cd = _orCachedBetSlip[key];
                if (cd) {
                    if (data[2]) {
                        cd[3] = data[2];
                    }
                    if (data[3]) {
                        cd[2] = data[3];
                    }
                    if (data[4]) {
                        cd[8] = cd[4];
                        cd[4] = data[4];
                    }
                    if (cd[11] == 2) {
                        cd[11] = 0;
                    }
                    cd[14] = data[5];
                }
            }
        }

        function _getInputBox(d, id, disabled) {
            var temp = [];
            temp['inputid'] = id;
            temp['index'] = d['index'];
            temp['value'] = (typeof (d[id]) != 'undefined') ? _addCommas(d[id]) : '';
            temp['onkeyup'] = id == 'stk' ? '$M(\'bs\').onStakeValueChanged(this,event);' : '$M(\'bs\').onWinValueChanged(this,event);';
            if (!disabled) {
                temp['tab-index'] = (id == 'stk' ? d['index'] * 2 : (d['index'] * 2) + 1) + 30;
            }
            var template = disabled ? _template['bet-slip-disabled-input-box'] : _template['bet-slip-input-box'];
            return template.getText(temp);
        }

        function _removeCommas(strValue) {
            return strValue.replace(/,/g, '');
        }

        function _addCommas(str) {
            if (!str) return '';
            str += '';
            str = _removeCommas(str);
            var b = str.split(".");
            var n = b[0];
            var a = [];
            while (n.length > 3) {
                var nn = n.substr(n.length - 3);
                a.unshift(nn);
                n = n.substr(0, n.length - 3);
            }
            if (n.length > 0) {
                a.unshift(n);
            }
            n = a.join(',');
            if (b.length == 2)
                n += "." + b[1];
            return n;
        }
        this.openForecast = function (isStakeChanged, event, fcOddsId, fcOddsOpt, fcOddsPrice, index) {
            var key = fcOddsId + '-' + fcOddsOpt;
            obj = _sCachedBetSlip[key];
            if (obj) {
                var stake = parseFloat(obj[20]);
                _fcCurrentFCKey = key;
                _fcAllFCStake[key] = stake;
                $M('fc').fcEnableTicketFCDiv(stake, isStakeChanged, event, fcOddsId, fcOddsPrice, fcOddsOpt, -1, index);
            }
        };

        function fcUpdFCOnStakeChange(obj, stake) {
            if (obj && $M('fc').fcIsTicketFcOpen()) {
                $M('fc').fcEnableTicketFCDiv(stake, true, 0, obj[0], obj[7], obj[9], -1, -1);
            }
        }

        function onFCStakeChange(cobj, stake, key) {
            if (_fcCurrentFCKey == key) {
                fcUpdFCOnStakeChange(cobj, stake);
            }
        }

        function removeForecastBet(key) {
            $M('fc').fcOnDeleteAllEvent(key);
        }

        function closeForecast() {
            $M('fc').fcOnHide();
        };
        this.onAddBetSlipCache = function (data, nodraw) {
            if (data) {
                var type = data[0];
                var ad = data[1];
                if (data[2] != undefined) {
                    _syn.bc = data[2];
                }
                var obj;
                var key;
                var i;
                if (ad) {
                    if (type) {
                        switch (type) {
                        case 's':
                            for (i = ad.length - 1; i >= 0; i--) {
                                obj = ad[i];
                                if (obj) {
                                    key = obj[0] + '-' + obj[9];
                                    if (_sCachedBetSlip[key] == undefined) {
                                        _orderedIds.unshift([type, key]);
                                        $M('od').onOptionSelected('s', key, true);
                                        obj[7] = getOValue(obj[7]);
                                        obj[16] = getOValue(obj[16]);
                                        _sCachedBetSlip[key] = obj;
                                    }
                                }
                            }
                            break;
                        case 'm':
                            for (i = ad.length - 1; i >= 0; i--) {
                                obj = ad[i];
                                if (obj) {
                                    key = obj[0] + '-' + obj[9];
                                    if (_mpCachedBetSlip[key] == undefined) {
                                        if (!_mid || _mid.length == 0) {
                                            _orderedIds.unshift([type, '']);
                                        }
                                        $M('od').onOptionSelected('m', key, true);
                                        _mid.unshift(key);
                                        _mpCachedBetSlip[key] = obj;
                                        if (_mpData[0]) {
                                            _mpData[0] = tilib_CorrectFloat(_mpData[0] * obj[7]);
                                        } else {
                                            _mpData[1] = 1;
                                            _mpData[0] = obj[7];
                                        }
                                        if (obj[2] != 1) {
                                            if (_mpData[4]) {
                                                _mpData[4] += 1;
                                            } else {
                                                _mpData[4] = 1;
                                            }
                                        }
                                        if (obj[25]) {
                                            _mpData[8] = true;
                                        }
                                    }
                                }
                            }
                            break;
                        case 'o':
                            for (i = ad.length - 1; i >= 0; i--) {
                                obj = ad[i];
                                if (obj) {
                                    key = obj[0] + '-' + (obj[6] ? '1' : '0');
                                    if (_orCachedBetSlip[key] == undefined) {
                                        $M('od').onOptionSelected('o', key, true);
                                        _orderedIds.unshift([type, key]);
                                        _orCachedBetSlip[key] = obj;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
            if (!nodraw) {
                _draw();
                if ($T('site').getValue('asi')) {
                    var e = document.getElementById('stk_0');
                    if ($M('fc').fcIsFromForecast()) {
                        e.value = $M('fc').fcGetSelectedBetStake();
                        $M('fc').fcResetFromForecast();
                    } else {
                        $M('fc').fcOnClose();
                    }
                    _target['stk_0'] = e
                    e.select();
                    try {
                        e.focus();
                    } catch (exp) {}
                }
            }
        }
        this.openDoublePromoTnC = function (link) {
            return tilib_PopUp('Double Promotion', link, {
                'sb': 'no',
                'w': 1024,
                'h': 600
            });
        }
        this.onRemoveBetSlipCache = function (index, isMP) {
            var mpIndex = -1;
            if (isMP) {
                mpIndex = index;
                for (var temp = 0; temp < _orderedIds.length; temp++) {
                    if (_orderedIds[temp][0] == 'm') {
                        index = temp;
                        break;
                    }
                }
            }
            if (index > -1) {
                if (_orderedIds.length - 1 >= index) {
                    var dict = _orderedIds[index];
                    if (dict) {
                        var type = dict[0];
                        var key = dict[1];
                        switch (type) {
                        case 's':
                            if (_sCachedBetSlip) {
                                $M('od').onOptionSelected('s', key, false);
                                delete _sCachedBetSlip[key];
                            }
                            break;
                        case 'm':
                            if (_mpCachedBetSlip) {
                                key = _mid[mpIndex];
                                var obj = _mpCachedBetSlip[key];
                                if (obj) {
                                    if (obj[2] != 1) {
                                        _mpData[4] -= 1;
                                    }
                                    _mpData[0] = tilib_CorrectFloat(_mpData[0] / obj[7]);
                                }
                                $M('od').onOptionSelected('m', key, false);
                                delete _mpCachedBetSlip[key];
                                _mid.splice(mpIndex, 1);
                            }
                            break;
                        case 'o':
                            if (_orCachedBetSlip) {
                                $M('od').onOptionSelected('o', key, false);
                                delete _orCachedBetSlip[key];
                            }
                            break;
                        }
                    }
                    if (!isMP || !_mid || _mid.length == 0) {
                        _orderedIds.splice(index, 1);
                    }
                    _draw();
                }
            }
        }
        this.onBetSlipClearCache = function (index, draw) {
            var key;
            var type;
            if (index == -1) {
                for (var i = 0; i < _orderedIds.length; i++) {
                    var dict = _orderedIds[i];
                    if (dict) {
                        type = dict[0];
                        key = dict[1];
                        if (type && type != 'm') {
                            $M('od').onOptionSelected(type, key, false);
                        }
                    }
                }
                _orderedIds = [];
                _sCachedBetSlip = [];
                _orCachedBetSlip = [];
            } else {
                _orderedIds.splice(index, 1);
            }
            for (var mid = 0; mid < _mid.length; mid++) {
                key = _mid[mid];
                if (key) {
                    $M('od').onOptionSelected('m', key, false);
                }
            }
            _mpCachedBetSlip = [];
            _mid = [];
            _mpData = [];
            if (draw) {
                _draw();
            }
        }
        this.onUpdateCacheCheckedAll = function (isChecked) {
            var obj;
            var value = isChecked ? 1 : 0;
            if (_sCachedBetSlip) {
                for (var sid in _sCachedBetSlip) {
                    obj = _sCachedBetSlip[sid];
                    if (obj && obj[19] != 2) {
                        obj[14] = value;
                    }
                }
            }
            if (_mpData && _mpData[3] != 2) {
                _mpData[1] = value;
            }
            if (_orCachedBetSlip) {
                for (var orid in _orCachedBetSlip) {
                    obj = _orCachedBetSlip[orid];
                    if (obj && obj[11] != 2) {
                        obj[7] = value;
                    }
                }
            }
            _draw();
        }
        this.onUpdateCacheCheck = function (index, isChecked) {
            if (isChecked != undefined && index > -1 && _orderedIds.length - 1 >= index) {
                var dict = _orderedIds[index];
                if (dict) {
                    var obj;
                    var value = isChecked ? 1 : 0;
                    var type = dict[0];
                    var key = dict[1];
                    switch (type) {
                    case 's':
                        if (_sCachedBetSlip) {
                            obj = _sCachedBetSlip[key];
                            if (obj) {
                                obj[14] = value;
                            }
                        }
                        break;
                    case 'm':
                        _mpData[1] = value;
                        break;
                    case 'o':
                        if (_orCachedBetSlip) {
                            obj = _orCachedBetSlip[key];
                            if (obj) {
                                obj[7] = value;
                            }
                        }
                    }
                }
            }
            _computeFooter();
            _draw();
        }
        this.onUpdateCacheData = function (data) {
            var hasUpdate = false;
            if (data) {
                hasUpdate = true;
                var updatedData = data[0];
                var deletedData = data[1];
                if (updatedData) {
                    _updateDataIntoCache(updatedData);
                }
                if (deletedData) {
                    _updateDeletedDataIntoCache(deletedData);
                }
            }
            if (hasUpdate && _syn.displayState == 0) {
                _computeFooter();
                _draw();
            }
        }
        this.onInitiate = function (data, nodraw, bc) {
            if (data) {
                for (var i = data.length - 1; i >= 0; i--) {
                    var obj = data[i];
                    if (obj) {
                        var type = obj[0];
                        var d = obj[1];
                        if (d) {
                            switch (type) {
                            case 's':
                            case 'o':
                                this.onAddBetSlipCache(obj);
                                break;
                            case 'm':
                                var mchk = obj[2];
                                if (d) {
                                    this.onAddBetSlipCache(['m', d]);
                                    _mpData[1] = mchk;
                                }
                                break;
                            }
                        }
                    }
                }
                if (bc) {
                    _syn.bc = bc;
                }
            }
            if (!nodraw) {
                _draw();
            }
        }
        this.onUpdateMPMaxBet = function (maxBet, totalPrice) {
            _mpData[2] = maxBet;
            if (totalPrice) {
                _mpData[0] = totalPrice;
            }
            _draw();
        }
        this.onShow = function () {
            _syn.displayState = 0;
            _draw();
            var e = document.getElementById('stk_0');
            if (e && $T('site').getValue('asi')) {
                _target['stk_0'] = e
                e.select();
                try {
                    e.focus();
                } catch (exp) {}
            }
        }
        this.onAddBetSlip = function (type, oid, sel, price) {
            var key = oid + '-' + sel;
            if ((type == 's' && _orderedIds.length >= 10 && !_sCachedBetSlip[key]) || (type == 'o' && _orderedIds.length >= 10 && !_orCachedBetSlip[key])) {
                alert(_translation['msg-max-bs']);
                return;
            }
            var pStyle = $T('od').getValue('ps');
            if ($T('site').getValue('asi')) {
                if ($M('fc').fcIsFromForecast()) {
                    pStyle = $M('fc').fcGetSelectedBetPStyle();
                    if (pStyle == -1) {
                        pStyle = $T('od').getValue('ps');
                    }
                } else {
                    closeForecast();
                }
            }
            var param = '?type=' + type + '&oid=' + oid + '&sel=' + sel + '&price=' + price + '&act=a&ps=' + pStyle + '&pid=' + $T('od').getValue('pid') + '&eVersion=' + $T('site').getValue('o-token');
            _submit(_url, param);
        }
        this.isOptionSelected = function (type, oid, sel) {
            var isSelected = false;
            var cache;
            if (type) {
                switch (type) {
                case 's':
                    cache = _sCachedBetSlip;
                    break;
                case 'm':
                    cache = _mpCachedBetSlip;
                    break;
                case 'o':
                    cache = _orCachedBetSlip;
                    break;
                }
                var key = oid + '-' + sel;
                if (cache[key]) {
                    isSelected = true;
                }
            }
            return isSelected;
        }
        this.onIdle = function () {
            var hasUpdate = false;
            var obj;
            var key;
            for (key in _sCachedBetSlip) {
                obj = _sCachedBetSlip[key];
                if (obj) {
                    if (obj[16] != obj[7]) {
                        hasUpdate = true;
                        obj[16] = obj[7];
                    }
                }
            }
            for (key in _mpCachedBetSlip) {
                obj = _mpCachedBetSlip[key];
                if (obj) {
                    if (obj[16] != obj[7]) {
                        obj[16] = obj[7];
                        hasUpdate = true;
                    }
                }
            }
            for (key in _orCachedBetSlip) {
                obj = _orCachedBetSlip[key];
                if (obj) {
                    if (obj[8] != obj[4]) {
                        obj[8] = obj[4];
                        hasUpdate = true;
                    }
                }
            }
            if (hasUpdate) {
                _draw();
            }
        }
        this.onRemoveBetSlip = function (index, isMp) {
            var mpIndex;
            if (isMp) {
                mpIndex = index;
                for (var i = 0; i < _orderedIds.length; i++) {
                    if (_orderedIds[i][0] == 'm') {
                        index = i;
                        break;
                    }
                }
            }
            if (index > -1 && _orderedIds && _orderedIds.length - 1 >= index) {
                var dict = _orderedIds[index];
                var param;
                if (dict) {
                    var type = dict[0];
                    var key = dict[1];
                    var obj;
                    switch (type) {
                    case 's':
                        if (_sCachedBetSlip) {
                            obj = _sCachedBetSlip[key];
                            if (obj) {
                                param = '?type=s&oid=' + obj[0] + '&sel=' + obj[9] + '&price=' + obj[7] + '&act=r' + '&eVersion=' + $T('site').getValue('o-token');
                                if (_fcCurrentFCKey == key) {
                                    $M('fc').fcOnClose();
                                }
                            }
                        }
                        break;
                    case 'm':
                        var mpKey = _mid[mpIndex];
                        if (mpKey) {
                            if (_mpCachedBetSlip) {
                                obj = _mpCachedBetSlip[mpKey];
                                if (obj) {
                                    param = '?type=m&oid=' + obj[0] + '&sel=' + obj[9] + '&price=' + obj[7] + '&act=r' + '&eVersion=' + $T('site').getValue('o-token');
                                }
                            }
                        }
                        break;
                    case 'o':
                        if (_orCachedBetSlip) {
                            obj = _orCachedBetSlip[key];
                            if (obj) {
                                param = '?type=o&oid=' + obj[0] + '&sel=' + obj[6] + '&price=' + obj[4] + '&act=r' + '&eVersion=' + $T('site').getValue('o-token');
                            }
                        }
                        break;
                    }
                    _submit(_url, param);
                }
            }
        }
        this.onClickAll = function (obj) {
            if (_orderedIds && _orderedIds.length > 0) {
                var param = '?act=' + (obj.checked ? 'chkall' : 'uchkall');
                _submit(_url, param);
            }
        }
        this.onCheck = function (obj) {
            var index = 0;
            var data = obj.id.split('_');
            var isMp = false;
            if (data && data[1] != undefined) {
                index = data[1];
                if (_orderedIds && _orderedIds.length - 1 >= index) {
                    var dict = _orderedIds[index];
                    if (dict) {
                        var param;
                        var type = dict[0];
                        var key = dict[1];
                        var co;
                        switch (type) {
                        case 's':
                            if (_sCachedBetSlip) {
                                co = _sCachedBetSlip[key];
                                if (co) {
                                    param = '?type=s&oid=' + co[0] + '&sel=' + co[9] + '&price=' + co[7] + '&act=' + (obj.checked ? 'chk' : 'uchk') + '&eVersion=' + $T('site').getValue('o-token');
                                }
                            }
                            break;
                        case 'm':
                            var mpKey = _mid[index];
                            if (mpKey) {
                                if (_mpCachedBetSlip) {
                                    co = _mpCachedBetSlip[mpKey];
                                    if (co) {
                                        param = '?type=m&oid=' + co[0] + '&sel=' + co[9] + '&price=' + co[7] + '&act=' + (obj.checked ? 'chk' : 'uchk') + '&eVersion=' + $T('site').getValue('o-token');
                                    }
                                }
                            }
                            break;
                        case 'o':
                            if (_orCachedBetSlip) {
                                co = _orCachedBetSlip[key];
                                if (co) {
                                    param = '?type=o&oid=' + co[0] + '&sel=' + co[6] + '&price=' + co[4] + '&act=' + (obj.checked ? 'chk' : 'uchk') + '&eVersion=' + $T('site').getValue('o-token');
                                }
                            }
                            break;
                        }
                        _submit(_url, param);
                    }
                }
            }
        }
        this.onClear = function (isMp) {
            var param = '?act=c' + '&eVersion=' + $T('site').getValue('o-token');
            if (isMp) {
                param += '&type=m';
            }
            $M('fc').fcOnClose();
            _submit(_url, param);
        }
        this.onUpdate = function () {
            var param = '?act=u';
            _submit(_url, param);
        }
        this.onReplace = function (data, draw) {
            this.onBetSlipClearCache(-1, false);
            this.onInitiate(data);
            if (draw) {
                _draw();
            }
        }
        this.onEachBet = function (obj, event) {
            var stake = _removeCommas(obj.value);
            var whichCode = (window.Event && event.which) ? event.which : event.keyCode;
            if (whichCode == 9 || (stake != "" && (stake <= 0 || !this.onValidateNumberFormat(obj, event)))) {
                return;
            }
            if (_orderedIds) {
                for (var index = 0; index < _orderedIds.length; index++) {
                    var valid = false;
                    var dict = _orderedIds[index];
                    if (dict) {
                        var type = dict[0];
                        var key = dict[1];
                        var maxBet = 0;
                        var cobj;
                        switch (type) {
                        case 's':
                            if (_sCachedBetSlip) {
                                cobj = _sCachedBetSlip[key];
                                if (cobj && cobj[14]) {
                                    valid = true;
                                    maxBet = cobj[18];
                                }
                            }
                            break;
                        case 'm':
                            if (_mid && _mid.length > 0) {
                                if (_mpData && _mpData[1]) {
                                    valid = true;
                                    maxBet = _mpData[2];
                                }
                            }
                            break;
                        case 'o':
                            if (_orCachedBetSlip) {
                                cobj = _orCachedBetSlip[key];
                                if (cobj && cobj[7]) {
                                    valid = true;
                                    maxBet = cobj[10];
                                }
                            }
                            break;
                        }
                        if (valid) {
                            var e = _getObjectWithId('stk_' + index);
                            e.value = (stake < maxBet || !$T('site').getValue('asi')) ? stake : maxBet;
                            this.onValidateNumberFormat(e, event);
                            this.onComputeWin(e);
                        }
                    }
                }
            }
        }
        this.onMaxBet = function (index) {
            if (_orderedIds && _orderedIds.length - 1 >= index) {
                var dict = _orderedIds[index];
                if (dict) {
                    var type = dict[0];
                    var key = dict[1];
                    var obj;
                    var value;
                    switch (type) {
                    case 's':
                        if (_sCachedBetSlip) {
                            obj = _sCachedBetSlip[key];
                            if (obj) {
                                value = obj[18];
                            }
                        }
                        break;
                    case 'm':
                        if (_mid && _mid.length > 0) {
                            if (_mpData) {
                                value = _mpData[2];
                            }
                        }
                        break;
                    case 'o':
                        if (_orCachedBetSlip) {
                            obj = _orCachedBetSlip[key];
                            if (obj) {
                                value = obj[10];
                            }
                        }
                        break;
                    }
                    var e = _getObjectWithId('stk_' + index);
                    try {
                        e.focus();
                    } catch (exp) {}
                    e.value = value;
                }
            }
            this.onComputeWin(e);
        }
        this.onWinValueChanged = function (obj, event) {
            if (this.onValidateNumberFormat(obj, event)) {
                this.onComputeStake(obj);
                var e = _getObjectWithId('each-bet');
                if (e) {
                    e.value = '';
                }
            }
        }
        this.onComputeStake = function (obj) {
            var index = 0;
            var data = obj.id.split('_');
            if (data && data[1] != undefined) {
                index = data[1];
            }
            if (_orderedIds && _orderedIds.length - 1 >= index) {
                var dict = _orderedIds[index];
                if (dict) {
                    var type = dict[0];
                    var key = dict[1];
                    var d;
                    var price;
                    var stake;
                    var towin = parseFloat(_removeCommas(obj.value));
                    var isValid = false;
                    switch (type) {
                    case 's':
                        if (_sCachedBetSlip) {
                            d = _sCachedBetSlip[key];
                            if (d) {
                                price = parseFloat(d[7]);
                                if (isNaN(towin)) {
                                    stake = '';
                                    d[20] = 0;
                                    d[21] = 0;
                                    onFCStakeChange(d, 0, key);
                                } else {
                                    var pStyle = $T('od').getValue('ps');
                                    var mktType = d[4];
                                    var oriPrice = price;
                                    if (pStyle && pStyle == 4 || bs_euroOddsMkt && mktType && bs_euroOddsMkt[mktType] == 1) {
                                        price = tilib_CorrectFloat(price - 1);
                                    }
                                    stake = (oriPrice < 0 ? Math.ceil(towin) : Math.ceil(towin / price));
                                    d[20] = tilib_CorrectFloat(stake);
                                    d[21] = tilib_CorrectFloat(towin);
                                    onFCStakeChange(d, stake, key);
                                }
                                isValid = true;
                            }
                        }
                        break;
                    case 'm':
                        if (_mid && _mid.length > 0) {
                            if (_mpData) {
                                if (isNaN(towin)) {
                                    stake = '';
                                    _mpData[6] = 0;
                                    _mpData[7] = 0;
                                } else {
                                    price = parseFloat(_mpData[0]);
                                    var oriPrice = price;
                                    price = tilib_CorrectFloat(price - 1);
                                    stake = (oriPrice < 0 ? Math.ceil(towin) : Math.ceil(towin / price));
                                    _mpData[6] = tilib_CorrectFloat(stake);
                                    _mpData[7] = tilib_CorrectFloat(towin);
                                }
                                isValid = true;
                            }
                        }
                        break;
                    case 'o':
                        if (_orCachedBetSlip) {
                            d = _orCachedBetSlip[key];
                            if (d) {
                                if (isNaN(towin)) {
                                    stake = '';
                                    d[12] = 0;
                                    d[13] = 0;
                                } else {
                                    price = parseFloat(d[4]);
                                    var oriPrice = price;
                                    price = tilib_CorrectFloat(price - 1);
                                    stake = (oriPrice < 0 ? Math.ceil(towin) : Math.ceil(towin / price));
                                    d[12] = tilib_CorrectFloat(stake);
                                    d[13] = tilib_CorrectFloat(towin);
                                }
                                isValid = true;
                            }
                        }
                        break;
                    }
                    var e = _getObjectWithId('stk_' + index);
                    if (isValid) {
                        e.value = _addCommas(stake);
                    } else {
                        e.value = '';
                    }
                    _computeFooter();
                }
            }
        }
        this.onStakeValueChanged = function (obj, event) {
            if (this.onValidateNumberFormat(obj, event)) {
                this.onComputeWin(obj);
                var e = _getObjectWithId('each-bet');
                if (e) {
                    e.value = '';
                }
            }
        }
        this.onComputeWin = function (obj) {
            var index = 0;
            var data = obj.id.split('_');
            if (data && data[1] != undefined) {
                index = data[1];
            }
            if (_orderedIds && _orderedIds.length - 1 >= index) {
                var dict = _orderedIds[index];
                if (dict) {
                    var type = dict[0];
                    var key = dict[1];
                    var cobj;
                    var price;
                    var stake = parseFloat(_removeCommas(obj.value));
                    var towin;
                    var isValid = false;
                    switch (type) {
                    case 's':
                        if (_sCachedBetSlip) {
                            cobj = _sCachedBetSlip[key];
                            if (cobj) {
                                if (isNaN(stake)) {
                                    towin = '';
                                    cobj[20] = 0;
                                    cobj[21] = 0;
                                    onFCStakeChange(cobj, 0, key);
                                } else {
                                    price = parseFloat(cobj[7]);
                                    var pStyle = $T('od').getValue('ps');
                                    var mktType = cobj[4];
                                    var oriPrice = price;
                                    if (pStyle && pStyle == 4 || bs_euroOddsMkt && mktType && bs_euroOddsMkt[mktType] == 1) {
                                        price = tilib_CorrectFloat(price - 1);
                                    }
                                    towin = oriPrice < 0 ? Math.round(stake) : tilib_CorrectFloat(price * stake);
                                    cobj[20] = stake;
                                    cobj[21] = towin;
                                    onFCStakeChange(cobj, stake, key);
                                }
                                isValid = true;
                            }
                        }
                        break;
                    case 'm':
                        if (_mid && _mid.length > 0) {
                            if (_mpData) {
                                price = tilib_RoundDown(parseFloat(_mpData[0]), 3);
                                if (isNaN(stake)) {
                                    towin = '';
                                    _mpData[5] = 0;
                                    _mpData[6] = 0;
                                } else {
                                    price = tilib_CorrectFloat(price - 1);
                                    towin = price < 0 ? towin : tilib_CorrectFloat(price * stake);
                                    _mpData[5] = stake;
                                    _mpData[6] = towin;
                                }
                                isValid = true;
                            }
                        }
                        break;
                    case 'o':
                        if (_orCachedBetSlip) {
                            cobj = _orCachedBetSlip[key];
                            if (cobj) {
                                if (isNaN(stake)) {
                                    towin = '';
                                    cobj[12] = 0;
                                    cobj[13] = 0;
                                } else {
                                    price = parseFloat(cobj[4]);
                                    price = tilib_CorrectFloat(price - 1);
                                    towin = price < 0 ? towin : tilib_CorrectFloat(price * stake);
                                    cobj[12] = stake;
                                    cobj[13] = towin;
                                }
                                isValid = true;
                            }
                        }
                        break;
                    }
                    var e = _getObjectWithId('payout_' + index);
                    if (isValid) {
                        if (towin !== '') {
                            towin = tilib_RoundDown(towin, 2).toFixed(2);
                        }
                        e.value = _addCommas(towin);
                    } else {
                        e.value = '';
                    }
                    _computeFooter();
                }
            }
        }
        this.onValidateNumberFormat = function (obj, e) {
            var whichCode = (window.Event && e.which) ? e.which : e.keyCode;
            if ((whichCode >= 48 && whichCode <= 57) || whichCode == 8 || (whichCode >= 96 && whichCode <= 105)) {
                var n = obj.value.replace(/,/g, "");
                if (whichCode == 8) {}
                obj.value = _addCommas(n);
                if (parseFloat(n) == 0) n = '';
                return true;
            }
            return false;
        }
        this.onValidateFormat = function (obj, e) {
            var whichCode = (window.Event && e.which) ? e.which : e.keyCode;
            if (whichCode == 13) {
                this.onPlaceOrder();
                return false;
            }
            if (whichCode == 9) return true;
            if ((whichCode >= 48 && whichCode <= 57) || whichCode == 8) {
                var n = obj.value.replace(/,/g, "");
                if (whichCode == 8) {
                    if (n.length != 0)
                        n = n.substr(0, n.length - 1);
                }
                if (parseFloat(n) == 0) n = '';
                return true;
            }
            e.returnValue = false;
            return false;
        }
        this.onPlaceOrder = function () {
            if (!$T('site').getValue('asi')) {
                alert(_translation['msg-sign-in-only']);
                clearLogin();
                document.getElementById('username').focus();
            } else {
                var sb = [];
                if (_orderedIds) {
                    var errorIndex = -1;
                    for (var index = 0; index < _orderedIds.length; index++) {
                        var dict = _orderedIds[index];
                        if (!document.getElementById("bsChk_" + index).checked) {
                            continue;
                        }
                        if (dict) {
                            var type = dict[0];
                            var key = dict[1];
                            var obj;
                            var errorMessage;
                            var minBet;
                            var maxBet;
                            var stake;
                            var e = _getObjectWithId('stk_' + index);
                            switch (type) {
                            case 's':
                                if (_sCachedBetSlip) {
                                    obj = _sCachedBetSlip[key];
                                    if (obj && obj[14]) {
                                        stake = parseFloat(obj[20]);
                                        minBet = parseFloat(obj[17]);
                                        maxBet = parseFloat(obj[18]);
                                        if (!isNaN(stake) && !isNaN(obj[21]) && stake >= minBet && stake <= maxBet) {
                                            sb.push(_generateBet(obj));
                                        } else {
                                            if (stake > maxBet) {
                                                errorMessage = _translation['msg-4-alert'];
                                                e.value = _addCommas(maxBet);
                                                this.onComputeWin(e);
                                            } else if (stake < minBet) {
                                                errorMessage = _translation['msg-13-alert'];
                                                e.value = _addCommas(minBet);
                                                this.onComputeWin(e);
                                            } else {
                                                errorMessage = _translation['msg-3'];
                                            }
                                            errorIndex = index;
                                        }
                                    }
                                }
                                break;
                            case 'm':
                                if (_mpCachedBetSlip) {
                                    var mp = [];
                                    var mpCount = 0;
                                    minBet = 0;
                                    for (var mid in _mpCachedBetSlip) {
                                        obj = _mpCachedBetSlip[mid];
                                        if (obj && obj[19] != 2) {
                                            mpCount++;
                                            minBet = obj[17];
                                            mp.push(_generateMPBet(obj));
                                        }
                                    }
                                    maxBet = parseFloat(_mpData[2]);
                                    if (mp && mpCount >= 3) {
                                        stake = parseFloat(_mpData[5]);
                                        if (_mpData && !isNaN(stake) && !isNaN(_mpData[6]) && stake >= minBet && stake <= maxBet) {
                                            sb.push('m:' + mp.join('~') + '~' + (_mpData[1] ? '1' : '0') + '_' + _mpData[5]);
                                        } else {
                                            if (stake > maxBet) {
                                                errorMessage = _translation['msg-4-alert'];
                                                e.value = maxBet;
                                                this.onComputeWin(e);
                                            } else if (stake < minBet) {
                                                errorMessage = _translation['msg-13-alert'];
                                                e.value = minBet;
                                                this.onComputeWin(e);
                                            } else {
                                                errorMessage = _translation['msg-3'];
                                            }
                                            errorIndex = index;
                                        }
                                    } else {
                                        errorIndex = index;
                                        errorMessage = _translation['msg-min-suborders'];
                                    }
                                }
                                break;
                            case 'o':
                                if (_orCachedBetSlip) {
                                    obj = _orCachedBetSlip[key];
                                    if (obj && obj[7]) {
                                        stake = parseFloat(obj[12]);
                                        minBet = parseFloat(obj[9]);
                                        maxBet = parseFloat(obj[10]);
                                        if (!isNaN(stake) && !isNaN(obj[13]) && stake >= minBet && stake <= maxBet) {
                                            sb.push(_generateORBet(obj));
                                        } else {
                                            if (stake > maxBet) {
                                                errorMessage = _translation['msg-4-alert'];
                                                e.value = maxBet;
                                                this.onComputeWin(e);
                                            } else if (stake < minBet) {
                                                errorMessage = _translation['msg-13-alert'];
                                                e.value = minBet;
                                                this.onComputeWin(e);
                                            } else {
                                                errorMessage = _translation['msg-3'];
                                            }
                                            errorIndex = index;
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                    if (errorIndex >= 0 && errorMessage.length > 0) {
                        alert(errorMessage);
                        var errorInput = _getObjectWithId('stk_' + errorIndex);
                        errorInput.select();
                        try {
                            errorInput.focus();
                        } catch (exp) {}
                        var eb = _getObjectWithId('each-bet');
                        if (eb) {
                            eb.value = '';
                        }
                        return;
                    }
                }
                if (sb.length == 0) {
                    alert(_translation['msg-min-one-order']);
                } else {
                    var param = '?act=ord&bc=' + _syn.bc;
                    param += '&orders=' + sb.join('|');
                    param += '&eVersion=' + $T('site').getValue('o-token');
                    if (confirm(_translation['msg-confirm-order'])) {
                        _submit(_orderUrl, param);
                    }
                }
            }
        }
        this.setAcceptBetterOdds = function (val) {
            if (val != undefined) {
                _acceptBetterOdds = val;
            }
        }
        this.onAcceptBetterOdds = function () {
            var e = document.getElementById("better-odds");
            if (e) {
                _acceptBetterOdds = e.checked;
                var param = '?act=acceptBetter&accept=';
                if (_acceptBetterOdds) {
                    param += '1';
                } else {
                    param += '0';
                }
                _submit(_orderUrl, param);
            }
        }
        this.onShowReceipt = function (data) {
            var sb = [];
            var fc = 0;
            if (data) {
                var rdSB = [];
                var rdStakeToWin = [0, 0];
                for (var i = 0; i < data.length; i++) {
                    var rd = data[i];
                    if (rd) {
                        var type = rd[0];
                        var obj = rd[1];
                        switch (type) {
                        case 's':
                            if (obj) {
                                var sr = _getSReceiptContent(obj, rdStakeToWin);
                                var dt = obj[0];
                                if (dt) {
                                    removeForecastBet(dt[1] + '-' + dt[2]);
                                }
                                if (sr.length > 0) {
                                    rdSB.push(sr);
                                }
                            }
                            break;
                        case 'm':
                            if (obj) {
                                var mr = _getMPReceiptContent(obj, rdStakeToWin);
                                if (mr.length > 0) {
                                    rdSB.push(mr);
                                }
                            }
                            break;
                        case 'o':
                            if (obj) {
                                var or = _getOReceiptContent(obj, rdStakeToWin);
                                if (or.length > 0) {
                                    rdSB.push(or);
                                }
                            }
                            break;
                        case 'f':
                            if (obj) {
                                fc = obj;
                            }
                        }
                    }
                }
                var d = [];
                d['count'] = rdSB.length;
                d['bs-currency'] = _syn.currency;
                d['tstake'] = tilib_RoundDown(rdStakeToWin[0], 2);
                d['max-payout'] = tilib_RoundDown(rdStakeToWin[0] + rdStakeToWin[1], 2).toFixed(2);
                d['bs-button-text'] = _translation['continue'];
                d['bs-button-function'] = '$M(\'bs\').onShow();$M(\'bl\').onOpen();';
                d['tab-index-submit'] = 1;
                d['bet-slip-footer'] = _template['bet-slip-footer'].getText(d);
                if (fc > 0) {
                    d['order-remain'] = fc;
                    d['bet-slip-remain-order'] = _template['bet-slip-remain-order'].getText(d);
                }
                d['bet-slip-header-top'] = _template['bet-receipt-header'].getText();
                d['bet-slip-content'] = rdSB.join('');
                sb.push(_template['bet-slip-header'].getText(d));
                _receiptContent = sb.join('');
                setTimeout('$M(\'bs\').showReceipt()', 10);
            } else {
                draw();
            }
        };
        this.setFocus = function () {
            var bsb = document.getElementById("submit-button");
            if (bsb) {
                bsb.focus();
                bsb.blur();
                bsb.focus();
            };
        };
        this.showReceipt = function () {
            var p = document.getElementById('bet-slip-content');
            if (p) {
                _target = [];
                _syn.displayState = 1;
                p.innerHTML = _receiptContent;
                var timeOut = _getTimeOutMilliSeconds();
                setTimeout('$M(\'bs\').setFocus()', timeOut);
            }
            $M('bl').onClosed();
            $M('bl').onUpdate();
        };

        function _draw() {
            var sb = [];
            var d = [];
            var od = [];
            var totalValidBet = 0;
            var hasNonMPBet = false;
            if (_orderedIds && _orderedIds.length > 0) {
                var count = _orderedIds.length;
                for (var index = 0; index < count; index++) {
                    var dict = _orderedIds[index];
                    if (dict) {
                        var type = dict[0];
                        var key = dict[1];
                        var obj;
                        var content;
                        switch (type) {
                        case 's':
                            if (_sCachedBetSlip) {
                                obj = _sCachedBetSlip[key];
                                if (obj) {
                                    content = _GetSOrderContent(index, obj);
                                    if (content.length > 0) {
                                        od.push(content);
                                    }
                                    if (obj[14]) {
                                        totalValidBet++;
                                    }
                                }
                            }
                            hasNonMPBet = true;
                            break;
                        case 'm':
                            if (_mid && _mpCachedBetSlip) {
                                content = _GetMOrderContent(index);
                                if (content.length > 0) {
                                    od.push(content);
                                }
                                if (_mpData && _mpData[1]) {
                                    totalValidBet++;
                                }
                            }
                            break;
                        case 'o':
                            if (_orCachedBetSlip) {
                                obj = _orCachedBetSlip[key];
                                if (obj) {
                                    content = _GetOOrderContent(index, obj);
                                    if (content.length > 0) {
                                        od.push(content);
                                    }
                                    if (obj[7]) {
                                        totalValidBet++;
                                    }
                                }
                            }
                            hasNonMPBet = true;
                            break;
                        }
                    }
                }
                d['count'] = totalValidBet;
                d['bs-button-text'] = _translation['place-bet'];
                d['bs-button-function'] = '$M(\'bs\').onPlaceOrder();';
                d['tab-index-each-bet'] = (count * 2) + 30;
                d['tab-index-submit'] = (count * 2) + 31;
                if (hasNonMPBet) {
                    d['bet-slip-accept-better-odds'] = _template['bet-slip-accept-better-odds'].getText(d);
                    if (!_acceptBetterOdds) {
                        d['bet-slip-accept-better-odds'] = d['bet-slip-accept-better-odds'].split('checked="checked"').join('');
                    }
                }
                d['bet-slip-play-all'] = _template['bet-slip-play-all'].getText(d);
                d['bet-slip-footer'] = _template['bet-slip-footer'].getText(d);
                d['bet-slip-header-top'] = _template['bet-slip-select-remove-all'].getText();
                d['bet-slip-content'] = od.join('');
                sb.push(_template['bet-slip-header'].getText(d));
            } else {
                if (!$T('site').getValue('asi')) {
                    d['extra-content'] = _template['bet-slip-empty-extra-info'].getText();
                }
                sb.push(_template['bet-slip-empty'].getText(d));
            }
            var p = document.getElementById('panel-bs');
            if (p) {
                p.innerHTML = _template['bet-slip-main'].getText({
                    "content": sb.join(''),
                    'InfoSiteDomain': $T('site').getValue('info-site-domain')
                });
                _target = [];
            }
            var defaultStakeValue = $T('site').getValue('ds');
            if (typeof defaultStakeValue == 'undefined') {
                defaultStakeValue = '';
            } else if (defaultStakeValue == 0) {
                if (lastSuccessStake != null)
                    defaultStakeValue = lastSuccessStake;
                else
                    defaultStakeValue = '';
            }
            var m = $M('bs');
            for (i = 0; i < count; i++) {
                stake = document.getElementById('stk_' + i);
                if (stake.value == '')
                    stake.value = defaultStakeValue;
                if (stake) {
                    m.onComputeWin(stake);
                }
            }
            if (_orderedIds && _orderedIds.length > 0) {
                _computeFooter();
                _displayCheckBoxes();
            }
        }

        function _displayCheckBoxes() {
            var totalCount = (_orderedIds ? _orderedIds.length : 0);
            var disableCount = 0;
            if (totalCount > 0) {
                var count = 0;
                var processedMp = 0;
                for (var i = 0; i < totalCount; i++) {
                    var dict = _orderedIds[i];
                    if (dict) {
                        var type = dict[0];
                        var key = dict[1];
                        var obj;
                        var isChecked = false;
                        switch (type) {
                        case 's':
                            obj = _sCachedBetSlip[key];
                            if (obj && obj[14]) {
                                isChecked = true;
                            } else if (obj && obj[19] == 2) {
                                disableCount++;
                            }
                            break;
                        case 'm':
                            if (_mpData && _mpData[1]) {
                                isChecked = true;
                            } else if (_mpData && _mpData[4]) {
                                disableCount++;
                            }
                            break;
                        case 'o':
                            obj = _orCachedBetSlip[key];
                            if (obj && obj[7]) {
                                isChecked = true;
                            } else if (obj && obj[11] == 2) {
                                disableCount++;
                            }
                            break;
                        }
                        var e = _getObjectWithId('bsChk_' + i);
                        if (isChecked) {
                            count++;
                            e.checked = true;
                        } else {
                            e.checked = false;
                        }
                    }
                }
                e = _getObjectWithId('selectAll');
                if ((count == totalCount - disableCount) && count > 0) {
                    e.checked = true;
                } else {
                    e.checked = false;
                }
            }
        }

        function _getCorrectScoreSuffix(suffix, hScore, aScore) {
            var ary = suffix.split('-');
            if (ary.length != 2) {
                return suffix;
            }
            var hSuffix = parseInt(ary[0], 10) + ((hScore == undefined) ? 0 : hScore);
            var aSuffix = parseInt(ary[1], 10) + ((aScore == undefined) ? 0 : aScore);
            return hSuffix + ' - ' + aSuffix;
        }

        function _getExceptionOptions(val) {
            if (val == undefined || val == '') {
                return '';
            }
            var sb = [];
            var ary = val.split(',');
            var dc = ary.length;
            var d = {};
            for (var i = 0; i < dc; i++) {
                if (i == dc - 1) {
                    d['value'] = ary[i];
                } else {
                    d['value'] = ary[i] + ',';
                }
                var eo = _template['exception-options-span'].getText(d);
                sb.push(' ' + eo);
            }
            d['value-exception-options'] = sb.join('');
            return _template['exception-options'].getText(d);
        }

        function _GetSOrderContent(i, data) {
            if (data) {
                var d = [];
                var me = $E('market-displays');
                var disabled = false;
                d['index'] = i;
                d['event-name'] = $Name(data[5]) + ' ' + _elemTranslation['vs'][1] + ' ' + $Name(data[6]);
                if (data[22] != undefined && data[22] != '') {
                    d['betTypeGroupName'] = data[22] + "<br />";
                } else {
                    d['betTypeGroupName'] = '';
                }
                if (data[11] == 1 && (data[4] == 4 || data[4] == 14)) {
                    var tempCode = (data[4] == 4) ? 'live_cs' : 'live_fhcs';
                    if (me[tempCode]) {
                        d['market-info'] = me[tempCode][1];
                    }
                } else {
                    if (me[data[4]]) {
                        d['market-info'] = me[data[4]][1];
                    }
                }
                var fcOddsId = data[0];
                var fcOddsOpt = data[9];
                var fcOddsPrice = 0;
                d['odds-selection'] = _getOddsOption(data[15]);
                if (data[11] && (data[4] == 4 || data[4] == 14)) {
                    d['odds-selection'] = _getCorrectScoreSuffix(d['odds-selection'], data[12], data[13]);
                }
                if (data[16] != data[7]) {
                    temp = [];
                    temp['bs-old-odds'] = tilib_GetPriceString(data[16]);
                    d['old-odds'] = _template['bet-slip-old-odds'].getText(temp);
                    temp['bs-new-odds'] = tilib_GetPriceString(data[7]);
                    d['current-odds'] = _template['bet-slip-new-odds'].getText(temp);
                    fcOddsPrice = data[16];
                } else {
                    d['current-odds'] = tilib_GetPriceString(data[7]);
                    fcOddsPrice = data[7];
                }
                d['status'] = data[11] ? 'Live' : '';
                var fcStake = 0;
                if ($T('site').getValue('asi')) {
                    temp = [];
                    temp['bs-currency'] = _syn.currency;
                    temp['bs-min-amount'] = data[17] ? _addCommas(data[17]) : 0;
                    temp['bs-max-amount'] = data[18] ? _addCommas(data[18]) : 0;
                    d['bs-min-max-bet'] = _template['bet-min-max-bet'].getText(temp);
                    d['bs-bet-max'] = _template['bet-slip-bet-max'].getText(d);
                    var sportsType = data[2];
                    var mktT = data[4];
                    if (sportsType == 1 && mktT != 13 && mktT != 39) {
                        var fc = {};
                        fc['fcOddsId'] = fcOddsId;
                        fc['fcOddsOpt'] = fcOddsOpt;
                        fc['fcOddsPrice'] = fcOddsPrice;
                        fc['index'] = i;
                        d['bs-forecast-icon'] = _template['bet-forecast-icon'].getText(fc);
                        fcStake = _fcAllFCStake[fcOddsId + '-' + fcOddsOpt];
                    } else {
                        d['bs-forecast-icon'] = '';
                    }
                } else {
                    d['bs-forecast-icon'] = '';
                }
                errorType = data[19];
                isClosed = errorType && errorType == 2;
                if (isClosed) {
                    d['input-check'] = _template['bet-slip-disabled-check-box'].getText(d);
                    d['bet-slip-error-msg'] = _template['bet-slip-error-message'].getText({
                        'bs-error-msg': _translation['msg-' + errorType]
                    });
                    d['status'] = 'Invalid';
                    data[14] = 0;
                    disabled = true;
                } else {
                    d['input-check'] = _template['bet-slip-check-box'].getText(d);
                    if (errorType) {
                        temp = [];
                        temp['bs-error-msg'] = _translation['msg-' + errorType];
                        d['bet-slip-error-msg'] = _template['bet-slip-error-message'].getText(temp);
                    }
                }
                d['double-promotion-disclaimer'] = data[25] ? _template['bet-slip-double-promotion-disclaimer'].getText(temp) : '';
                if (fcStake != undefined && fcStake != 0) {
                    d['stk'] = fcStake;
                } else {
                    d['stk'] = data[20];
                }
                d['payout'] = data[21];
                d['input-stake'] = _getInputBox(d, 'stk', disabled);
                d['input-payout'] = _getInputBox(d, 'payout', disabled);
                var gmtSuffix = (data[3] && data[8]) ? _gmtHKTimeZone : '';
                d['info-title'] = data[3] + ' - ' + data[8] + gmtSuffix;
                if (data[4] && bs_euroOddsMktWithPoint[data[4]] == 0) {
                    d['point'] = '';
                } else {
                    d['point'] = _getPointDisplay(data[10]);
                }
                d['homeawayscore'] = data[11] ? _getHomeAwayScore(data[12], data[13]) : '';
                d['bs-currency'] = _syn.currency;
                d['checked'] = data[14] == 1 ? "checked = 'checked'" : "";
                d['exception-options'] = _getExceptionOptions(data[23]);
                d['rowKey'] = fcOddsId + '-' + fcOddsOpt;
                if (data[24]) {
                    d['alert'] = 'Alert';
                    d['alert-icon'] = _template['alert-icon'].getText(d);
                }
                return (_template['bet-slip-single-body'].getText(d));
            }
            return '';
        }

        function _GetMOrderContent(i) {
            var subs = [];
            var disabled = false;
            if (_mid && _mid.length > 0 && _mpCachedBetSlip) {
                var d = [];
                var userMin = 0;
                var disabledCount = 0;
                for (var mIndex = 0; mIndex < _mid.length; mIndex++) {
                    var mKey = _mid[mIndex];
                    var mpd = _mpCachedBetSlip[mKey];
                    if (mpd) {
                        if (mpd[20] !== undefined) {
                            _mpData[5] = mpd[20];
                        }
                        userMin = mpd[17] ? mpd[17] : 0;
                        subs.push(_GetMPSubOrderContent(mIndex, mpd));
                        if (mpd[19] == 2) {
                            disabledCount++;
                        } else if (mpd[19] && mpd[19] > 0) {
                            _mpData[3] = mpd[19];
                        }
                    }
                }
                d['index'] = i;
                d['mp-suborders'] = subs.join('');
                d['bs-mp-total-price'] = _mpData[0] != undefined ? tilib_GetPriceString(tilib_RoundDown(_mpData[0], 3)) : "0.00";
                d['stk'] = _addCommas(_mpData[5]);
                d['payout'] = _mpData[6];
                if (disabledCount == _mid.length) {
                    _mpData[1] = 0;
                    _mpData[3] = 2;
                    disabled = true;
                    d['input-check'] = _template['bet-slip-disabled-check-box'].getText(d);
                    d['status'] = 'Invalid';
                } else {
                    d['input-check'] = _template['bet-slip-check-box'].getText(d);
                    d['status'] = '';
                }
                d['double-promotion-disclaimer'] = _mpData[8] ? _template['bet-slip-double-promotion-disclaimer'].getText() : '';
                d['input-stake'] = _getInputBox(d, 'stk', disabled);
                d['input-payout'] = _getInputBox(d, 'payout', disabled);
                if ($T('site').getValue('asi')) {
                    temp = [];
                    temp['bs-currency'] = _syn.currency;
                    temp['bs-min-amount'] = _addCommas(userMin);
                    temp['bs-max-amount'] = _addCommas(_mpData[2]);
                    d['bs-min-max-bet'] = _template['bet-min-max-bet'].getText(temp);
                    errorType = _mpData && _mpData[3];
                    if (errorType) {
                        temp = [];
                        temp['bs-error-msg'] = _translation['msg-' + errorType];
                        d['bet-slip-error-msg'] = _template['bet-slip-error-message'].getText(temp);
                    }
                    d['bs-bet-max'] = _template['bet-slip-bet-max'].getText(d);
                }
                return (_template['bet-slip-mp-body'].getText(d));
            }
            return '';
        }

        function _GetMPSubOrderContent(mi, sub) {
            if (sub) {
                var d = [];
                var sid = sub[2];
                if (sid == 25 && $T('site').getValue('bigevent-rid')) {
                    sid = 'Oly';
                }
                var me = $E('market-displays');
                d['index'] = mi;
                d['sport-id'] = sid;
                var gmtSuffix = (sub[3] && sub[8]) ? _gmtHKTimeZone : '';
                d['info-title'] = sub[3] + ' - ' + sub[8] + gmtSuffix;
                if (sub[2] != 1) isAllSoccer = false;
                d['event-name'] = $Name(sub[5]) + ' ' + _elemTranslation['vs'][1] + ' ' + $Name(sub[6]);
                if (sub[22] != undefined && sub[22] != '') {
                    d['betTypeGroupName'] = sub[22] + "<br />";
                } else {
                    d['betTypeGroupName'] = '';
                }
                if (me[sub[4]]) {
                    d['market-info'] = me[sub[4]][1];
                    d['odds-selection'] = _getOddsOption(sub[15]);
                }
                var errorType = sub[19];
                var isClosed = errorType && errorType == 2;
                d['status'] = isClosed ? 'Invalid' : '';
                if (sub[16] != sub[7] && !isClosed) {
                    var temp = [];
                    temp['bs-old-odds'] = tilib_GetPriceString(sub[16]);
                    d['old-odds'] = _template['bet-slip-old-odds'].getText(temp);
                    temp['bs-new-odds'] = tilib_GetPriceString(sub[7]);
                    d['current-odds'] = _template['bet-slip-new-odds'].getText(temp);
                } else {
                    d['current-odds'] = tilib_GetPriceString(sub[7]);
                }
                if (sub[4] && bs_euroOddsMktWithPoint[sub[4]] == 0) {
                    d['point'] = '';
                } else {
                    d['point'] = _getPointDisplay(sub[10]);
                }
                d['homeawayscore'] = sub[11] ? _getHomeAwayScore(sub[12], sub[13]) : '';
                return _template['bet-slip-mp-suborders'].getText(d);
            }
        }

        function _GetOOrderContent(i, data) {
            if (data) {
                var d = [];
                var disabled = false;
                var me = $E('market-displays');
                d['index'] = i;
                d['event-name'] = data[2];
                if (me[39]) {
                    d['market-info'] = me[39][1];
                }
                d['odds-selection'] = data[3];
                if (data[8] != data[4]) {
                    temp = [];
                    temp['bs-old-odds'] = tilib_GetPriceString(data[8]);
                    d['old-odds'] = _template['bet-slip-old-odds'].getText(temp);
                    temp['bs-new-odds'] = tilib_GetPriceString(data[4]);
                    d['current-odds'] = _template['bet-slip-new-odds'].getText(temp);
                } else {
                    d['current-odds'] = tilib_GetPriceString(data[4]);
                }
                d['status'] = data[6] ? 'Live' : '';
                if ($T('site').getValue('asi')) {
                    temp = [];
                    temp['bs-currency'] = _syn.currency;
                    temp['bs-min-amount'] = data[9] ? _addCommas(data[9]) : 0;
                    temp['bs-max-amount'] = data[10] ? _addCommas(data[10]) : 0;
                    d['bs-min-max-bet'] = _template['bet-min-max-bet'].getText(temp);
                    d['bs-bet-max'] = _template['bet-slip-bet-max'].getText(d);
                }
                errorType = data[11];
                isClosed = errorType && errorType == 2;
                if (isClosed) {
                    if (!_isOddsClosed) {
                        alert(_translation['msg-' + errorType]);
                        _isOddsClosed = true;
                    }
                    d['input-check'] = _template['bet-slip-disabled-check-box'].getText(d);
                    d['status'] = 'Invalid';
                    data[7] = 0;
                    disabled = true;
                } else {
                    d['input-check'] = _template['bet-slip-check-box'].getText(d);
                    if (errorType) {
                        temp = [];
                        temp['bs-error-msg'] = _translation['msg-' + errorType];
                        d['bet-slip-error-msg'] = _template['bet-slip-error-message'].getText(temp);
                    }
                }
                d['double-promotion-disclaimer'] = data[14] ? _template['bet-slip-double-promotion-disclaimer'].getText() : '';
                d['stk'] = data[12];
                d['payout'] = data[13];
                d['input-stake'] = _getInputBox(d, 'stk', disabled);
                d['input-payout'] = _getInputBox(d, 'payout', disabled);
                var objDate = new Date(data[5]);
                var day = objDate.getDay();
                day = day < 10 ? '0' + day : day;
                var month = objDate.getMonth();
                month = month < 10 ? '0' + month : month;
                d['info-title'] = month + '/' + day + '/' + objDate.getFullYear();
                d['bs-currency'] = _syn.currency;
                d['checked'] = data[7] == 1 ? "checked = 'checked'" : "";
                return (_template['bet-slip-single-body'].getText(d));
            }
            return '';
        }

        function _getSReceiptContent(datas, arr) {
            if (datas) {
                var data = datas[0];
                var me = $E('market-displays');
                var d = [];
                var key = data[1] + '-' + data[2];
                $M('od').onOptionSelected('s', key, false);
                var mktType = data[3];
                var price = data[6];
                d['bs-receipt-ref'] = data[0];
                d['event-name'] = $Name(data[4]) + ' ' + _elemTranslation['vs'][1] + ' ' + $Name(data[5]);
                if (data[14] != undefined && data[14] != '') {
                    d['betTypeGroupName'] = data[14] + "<br />";
                } else {
                    d['betTypeGroupName'] = '';
                }
                if (data[9] && (mktType == 4 || mktType == 14)) {
                    var tempCode = (mktType == 4) ? 'live_cs' : 'live_fhcs';
                    d['market-info'] = me[tempCode][1];
                } else {
                    if (me[mktType]) {
                        d['market-info'] = me[mktType][1];
                    }
                }
                if (mktType && bs_euroOddsMktWithPoint[mktType] == 0) {
                    d['point'] = '';
                } else {
                    d['point'] = _getPointDisplay(data[8]);
                }
                d['homeawayscore'] = data[9] ? _getHomeAwayScore(data[10], data[11]) : '';
                d['status'] = data[9] ? 'Live' : '';
                d['odds-selection'] = _getOddsOption(data[7]);
                if (data[9] && (data[3] == 4 || data[3] == 14)) {
                    d['odds-selection'] = _getCorrectScoreSuffix(d['odds-selection'], data[10], data[11]);
                }
                d['final-price'] = tilib_GetPriceString(price);
                d['bs-currency'] = _syn.currency;
                d['final-stake'] = tilib_RoundDown(data[12], 2);
                d['receipt-status'] = _translation['status' + data[13]];
                d['exception-options'] = _getExceptionOptions(data[15]);
                var tempToWin = 0;
                if (price < 0) {
                    tempToWin = parseFloat(data[12]);
                }
                if (price > 0) {
                    var pStyle = $T('od').getValue('ps');
                    if (pStyle && pStyle == 4 || bs_euroOddsMkt && mktType && bs_euroOddsMkt[mktType] == 1) {
                        price = tilib_CorrectFloat(price - 1);
                    }
                    tempToWin = tilib_CorrectFloat(price * parseFloat(data[12]));
                }
                d['final-towin'] = tempToWin;
                arr[0] += isNaN(data[12]) ? 0 : parseFloat(data[12]);
                arr[1] = arr[1] + parseFloat(tempToWin);
                lastSuccessStake = parseInt(data[12]);
                return _template['bet-receipt-single'].getText(d);
            }
        }

        function _getOReceiptContent(datas, arr) {
            if (datas) {
                var data = datas[0];
                var me = $E('market-displays');
                var d = [];
                d['bs-receipt-ref'] = data[0];
                d['event-name'] = data[3];
                if (me[data[2]]) {
                    d['market-info'] = me[data[2]][1];
                }
                var key = data[1] + '-' + (data[6] ? "1" : "0");
                $M('od').onOptionSelected('o', key, false);
                var price = data[5];
                d['odds-selection'] = data[4];
                d['final-price'] = tilib_GetPriceString(price);
                d['status'] = data[6] ? 'Live' : '';
                d['bs-currency'] = _syn.currency;
                d['final-stake'] = tilib_RoundDown(data[7], 2).toFixed(2);
                d['receipt-status'] = _translation['status' + data[8]];
                var tempToWin = 0;
                if (price < 0) {
                    tempToWin = parseFloat(data[7]);
                }
                if (price > 0) {
                    price = tilib_CorrectFloat(price - 1);
                    tempToWin = tilib_RoundDown(price * parseFloat(data[7]), 3);
                }
                d['final-towin'] = tilib_RoundDown(tempToWin, 2).toFixed(2);
                arr[0] += isNaN(data[7]) ? 0 : parseFloat(data[7]);
                arr[1] = tilib_RoundDown(arr[1] + parseFloat(tempToWin), 2);
                return _template['bet-receipt-single'].getText(d);
            }
        }

        function _getMPReceiptContent(datas, arr) {
            if (datas) {
                var me = $E('market-displays');
                var count = datas.length;
                if (count > 0) {
                    var suborders = [];
                    var mpTotalPrice = 1;
                    var key;
                    for (var mpi = 0; mpi < datas.length; mpi++) {
                        var sub = [];
                        var mpd = datas[mpi];
                        if (mpd) {
                            key = mpd[1] + '-' + mpd[2];
                            $M('od').onOptionSelected('m', key, false);
                            sub['event-name'] = $Name(mpd[4]) + ' ' + _elemTranslation['vs'][1] + ' ' + $Name(mpd[5]);
                            if (mpd[14] != undefined && mpd[14] != '') {
                                sub['betTypeGroupName'] = mpd[14] + "<br />";
                            } else {
                                sub['betTypeGroupName'] = '';
                            }
                            if (me[mpd[3]]) {
                                sub['market-info'] = me[mpd[3]][1];
                            }
                            if (mpd[3] && bs_euroOddsMktWithPoint[mpd[3]] == 0) {
                                sub['point'] = '';
                            } else {
                                sub['point'] = _getPointDisplay(mpd[8]);
                            }
                            sub['odds-selection'] = _getOddsOption(mpd[7]);
                            sub['final-price'] = tilib_GetPriceString(mpd[6]);
                            mpTotalPrice = tilib_CorrectFloat(mpTotalPrice * mpd[6]);
                            suborders.push(_template['bet-mp-subreceipt'].getText(sub));
                        }
                    }
                    mpTotalPrice = tilib_RoundDown(mpTotalPrice, 3);
                    d['bs-receipt-ref'] = datas[0][0];
                    d['bs-mp-subreceipt'] = suborders.join('');
                    d['bs-mp-receipt-total-price'] = tilib_GetPriceString(mpTotalPrice);
                    d['bs-currency'] = _syn.currency;
                    d['receipt-status'] = _translation['status1'];
                    var stake = datas[0][12];
                    d['final-stake'] = stake;
                    mpTotalPrice = tilib_CorrectFloat(mpTotalPrice - 1);
                    tempToWin = tilib_CorrectFloat(mpTotalPrice * stake);
                    tempToWin = tilib_RoundDown(tempToWin, 2).toFixed(2);
                    d['final-towin'] = tempToWin;
                    arr[0] += isNaN(stake) ? 0 : parseFloat(stake);
                    arr[1] = tilib_RoundDown(arr[1] + parseFloat(tempToWin), 2);
                }
                return (_template['bet-receipt-mp'].getText(d));
            }
            return '';
        }

        function _getPointDisplay(point) {
            point *= 1;
            point = point.toFixed(2);
            if (point > 0) {
                point += '';
                if (point.indexOf('+') == -1) {
                    return ':+' + point;
                }
            }
            return ':' + point;
        }

        function _getHomeAwayScore(home, away) {
            return ' @ ' + home + ' - ' + away;
        }

        function _getOddsOption(option) {
            if (isNaN(option)) {
                return $Name(option);
            } else {
                var optionId = parseFloat(option);
                if (_oe[optionId]) {
                    return _oe[optionId][1];
                }
                return $Name(option);
            }
        }

        function _getObjectWithId(id) {
            var e = _target[id];
            if (!e) {
                e = document.getElementById(id);
                _target[id] = e;
            }
            return e;
        }

        function _getTimeOutMilliSeconds() {
            var userAgent = navigator.userAgent.toLowerCase();
            if (userAgent.indexOf("msie 7.0") > -1 || userAgent.indexOf("msie 8.0") > -1) {
                return 1000;
            } else {
                return 1;
            };
        };
    }

    function bl_EuroModel(url, currency, refreshRate) {
        var _translation = $P.getTranslation('bs');
        var _elemTranslation = $E('translation');
        var _oe = $E('odds-option');
        var _url = url;
        var _template = tilib_GenerateTemplates($P.getTemplate('bl'));
        var _target = [];
        var _cache = {};
        var _ocache;
        var _syn = {
            currency: currency,
            openState: true,
            version: -1,
            cooldownCount: 0,
            drawing: false,
            failureCount: 0,
            refreshRate: refreshRate,
            refreshCount: 0,
            initiated: false,
            rejectedCount: 0
        };
        this.onUpdate = function () {
            _submit(_url, '?v=' + _syn.version);
        }
        this.onAddUpdateBetList = function (data) {
            if (data) {
                var id = data[1];
                _cache[id] = data;
            }
        }
        this.onRemoveBetList = function (id) {
            if (id) {
                delete _cache[id];
            }
        }
        this.onTime = function () {
            if (_syn.cooldownCount) {
                _syn.cooldownCount--;
            } else {
                if ((_ocache && _ocache.length > 0) || !_syn.initiated || _syn.rejectedCount) {
                    if (_syn.drawing) {
                        if (_syn.failureCount > 3) {
                            _syn.drawing = false;
                        } else {
                            _syn.failureCount++;
                        }
                    } else if (_syn.refreshCount > 0) {
                        _drawRefreshButtons();
                        --_syn.refreshCount;
                    } else {
                        _syn.refreshCount = _syn.refreshRate;
                        _syn.drawing = true;
                        if (_syn.failureCount) {
                            _syn.failureCount = 0;
                        }
                        _syn.refreshCount = _syn.refreshRate;
                        if (!_syn.initiated) {
                            _syn.initiated = 1;
                        }
                        this.onUpdate();
                        _setCoolDown();
                    }
                }
            }
        }
        this.onOpenClose = function () {
            var e = _target['bl-panel'];
            if (!e) {
                e = document.getElementById('bl-panel');
                _target['bl-panel'] = e;
            }
            _syn.openState = !_syn.openState;
            var value = _syn.openState ? 'Open' : 'Closed';
            e.className = _template['class-div-panel'].getText({
                'open-closed': value
            });
        }
        this.onOpen = function () {
            if (!_syn.openState) {
                this.onOpenClose();
            }
            _draw();
        }
        this.onClosed = function () {
            if (_syn.openState) {
                this.onOpenClose();
            }
        }
        this.onIdle = function () {
            if (_syn.openState) {
                _draw();
            } else {
                _syn.drawing = false;
                _drawRefreshButtons();
            }
        }
        this.onRefresh = function () {
            if (!_syn.cooldownCount) {
                if (_ocache && _ocache.length > 0 || !_syn.initiated) {
                    if (_syn.drawing) {
                        if (_syn.failureCount > 3) {
                            _syn.drawing = false;
                        } else {
                            _syn.failureCount++;
                        }
                    } else {
                        _syn.refreshCount = _syn.refreshRate;
                        _syn.drawing = true;
                        if (_syn.failureCount) {
                            _syn.failureCount = 0;
                        }
                        this.onUpdate();
                        _setCoolDown();
                    }
                }
            }
        };
        this.onUpdateCacheData = function (data, version) {
            if (data) {
                var count;
                var updateData = data[0];
                var deleteData = data[1];
                var hasUpdatedData = false;
                var i = 0;
                if (updateData) {
                    count = updateData.length;
                    for (i = 0; i < count; i++) {
                        this.onAddUpdateBetList(updateData[i]);
                    }
                }
                if (deleteData) {
                    count = deleteData.length;
                    for (i = 0; i < count; i++) {
                        this.onRemoveBetList(deleteData[i]);
                    }
                }
                _syn.version = version;
                _syn.rejectedCount = data[2];
                this.onResort();
                if (_syn.openState) {
                    this.onOpen();
                }
            }
        }
        this.onResort = function () {
            if (_cache) {
                var ocache = [];
                for (var id in _cache) {
                    var d = _cache[id];
                    if (d) {
                        ocache.push(d);
                    }
                }
                ocache.sort(bl_SortByDate);
                _ocache = ocache;
                if (_ocache && _ocache.length == 0) {
                    _drawRefreshButtons();
                }
            }
        }

        function _draw() {
            var sb = [];
            var d = [];
            if (_ocache && _ocache.length > 0) {
                d['content'] = _getBetListContent();
            } else {
                d['content'] = _template['bet-list-empty'].getText();
            }
            if (_syn.rejectedCount) {
                d['rejected-bet-count'] = _syn.rejectedCount;
                d['bet-rejected'] = _template['bet-rejected'].getText(d);
            }
            sb.push(_template['bet-list-content'].getText(d));
            var p = document.getElementById('panel-bl');
            if (p) {
                d['class-div-panel'] = _template['class-div-panel'].getText({
                    'open-closed': 'Open'
                });
                d['bl-content'] = sb.join('');
                p.innerHTML = _template['bet-list-mini'].getText(d);
                _target = [];
                _syn.drawing = false;
                _drawRefreshButtons();
            }
        }

        function _addCommas(str) {
            str += '';
            var b = str.split(".");
            var n = b[0];
            var a = [];
            while (n.length > 3) {
                var nn = n.substr(n.length - 3);
                a.unshift(nn);
                n = n.substr(0, n.length - 3);
            }
            if (n.length > 0) {
                a.unshift(n);
            }
            n = a.join(',');
            if (b.length == 2)
                n += "." + b[1];
            return n;
        }

        function _getCorrectScoreSuffix(suffix, hScore, aScore) {
            var ary = suffix.split('-');
            if (ary.length != 2) {
                return suffix;
            }
            var hSuffix = parseInt(ary[0], 10) + ((hScore == undefined) ? 0 : hScore);
            var aSuffix = parseInt(ary[1], 10) + ((aScore == undefined) ? 0 : aScore);
            return hSuffix + ' - ' + aSuffix;
        }

        function _getExceptionOptions(val) {
            if (val == undefined || val == '') {
                return '';
            }
            var sb = [];
            var ary = val.split(',');
            var dc = ary.length;
            var d = {};
            for (var i = 0; i < dc; i++) {
                if (i == dc - 1) {
                    d['value'] = ary[i];
                } else {
                    d['value'] = ary[i] + ',';
                }
                var eo = _template['exception-options-span'].getText(d);
                sb.push(' ' + eo);
            }
            d['value-exception-options'] = sb.join('');
            return _template['exception-options'].getText(d);
        }

        function _getBetListContent() {
            var sb = [];
            var me = $E('market-displays');
            if (_ocache) {
                var c = _ocache.length;
                for (var i = 0; i < c; i++) {
                    var d = _ocache[i];
                    if (d) {
                        var sid = d[2];
                        if (sid == 25 && $T('site').getValue('bigevent-rid')) {
                            sid = 'Oly';
                        }
                        if (d[0] == 's') {
                            var h = [];
                            h['ref-no'] = d[1];
                            h['sport-id'] = sid;
                            h['tournament'] = d[3];
                            if (d[12] == 1 && (d[4] == 4 || d[4] == 14)) {
                                var tempCode = (d[4] == 4) ? 'live_cs' : 'live_fhcs';
                                h['market'] = me[tempCode][1];
                            } else {
                                h['market'] = me[d[4]][1];
                            }
                            h['point'] = _getPointDisplay(d[5]);
                            h['price'] = tilib_GetPriceString(d[6]);
                            h['price-style'] = d[7];
                            h['selection'] = _getOddsOption(d[8], d[4]);
                            if (d[12] && (d[4] == 4 || d[4] == 14)) {
                                h['selection'] = _getCorrectScoreSuffix(h['selection'], d[13], d[14]);
                            }
                            var dateTime = getDateObject(d[9]);
                            var month = dateTime.getMonth();
                            var date = dateTime.getDate();
                            var hours = dateTime.getHours();
                            var minutes = dateTime.getMinutes();
                            var seconds = dateTime.getSeconds();
                            h['date'] = (month < 10 ? '0' + month : month) + '/' +
                                (date < 10 ? '0' + date : date) + ' ' +
                                (hours < 10 ? '0' + hours : hours) + ':' +
                                (minutes < 10 ? '0' + minutes : minutes) + ':' +
                                (seconds < 10 ? '0' + seconds : seconds);
                            h['home'] = d[10] + ' ';
                            h['away'] = _elemTranslation['vs'][1] + ' ' + d[11];
                            if (d[17] != undefined && d[17] != '') {
                                h['betTypeGroupName'] = "<br />" + d[17];
                            } else {
                                h['betTypeGroupName'] = '';
                            }
                            h['status'] = d[12] ? 'Live' : '';
                            h['livescore'] = d[12] ? _getHomeAwayScore(d[13], d[14]) : '';
                            h['stake'] = _syn.currency + _addCommas(d[15]);
                            h['bl-status'] = _translation['status' + d[16]];
                            h['exception-options'] = _getExceptionOptions(d[18]);
                            var tempPayOut = 0;
                            if (d[6] < 0) {
                                tempPayOut = parseFloat(d[15]);
                            }
                            if (d[6] > 0) {
                                var tempPrice = d[6];
                                if (d[7] == 'E' || (bs_euroOddsMkt && bs_euroOddsMkt[d[4]] == 1)) {
                                    tempPrice = (tempPrice * 1000 - 1000) / 1000;
                                }
                                tempPayOut = (tempPrice * 1000 * parseFloat(d[15])) / 1000;
                            }
                            h['payout'] = _syn.currency + _addCommas((Math.round(tempPayOut * 100) / 100).toFixed(2));
                            h['list-content'] = _template['single-content'].getText(h);
                            sb.push(_template['bet-content'].getText(h));
                        } else {
                            var h = [];
                            h['ref-no'] = d[1];
                            h['sport-id'] = sid;
                            h['tournament'] = d[3];
                            h['market'] = me[d[4]][1];
                            h['price'] = tilib_GetPriceString(d[5]);
                            h['price-style'] = d[6];
                            h['selection'] = d[7];
                            var dateTime = getDateObject(d[8]);
                            var month = dateTime.getMonth();
                            var date = dateTime.getDate();
                            var hours = dateTime.getHours();
                            var minutes = dateTime.getMinutes();
                            var seconds = dateTime.getSeconds();
                            h['date'] = (month < 10 ? '0' + month : month) + '/' +
                                (date < 10 ? '0' + date : date) + ' ' +
                                (hours < 10 ? '0' + hours : hours) + ':' +
                                (minutes < 10 ? '0' + minutes : minutes) + ':' +
                                (seconds < 10 ? '0' + seconds : seconds);
                            h['status'] = d[9] ? 'Live' : '';
                            h['stake'] = _syn.currency + _addCommas(d[10]);
                            h['bl-status'] = _translation['status' + d[11]];
                            var tempPayOut = 0;
                            if (d[5] < 0) {
                                tempPayOut = parseFloat(d[10]);
                            }
                            if (d[5] > 0) {
                                var tempPrice = d[5];
                                if (d[6] == 'E' || (bs_euroOddsMkt && bs_euroOddsMkt[d[4]] == 1)) {
                                    tempPrice = (tempPrice * 1000 - 1000) / 1000;
                                }
                                tempPayOut = (tempPrice * 1000 * parseFloat(d[10])) / 1000;
                            }
                            h['payout'] = _syn.currency + _addCommas((Math.round(tempPayOut * 100) / 100).toFixed(2));
                            h['list-content'] = _template['outright-content'].getText(h);
                            sb.push(_template['bet-content'].getText(h));
                        }
                    }
                }
            }
            return sb.join('');
        }

        function _submit(url, param) {
            $P.sendRequest('bl', url + param);
            param = undefined;
        }

        function getDateObject(dateString) {
            if (dateString) {
                var dateTime = dateString.split(' ');
                var days;
                var months;
                var years;
                if (dateTime) {
                    var date = dateTime[0];
                    if (date) {
                        years = date.substr(0, 4);
                        months = date.substr(5, 2);
                        days = date.substr(8, 2);
                    }
                    var time = dateTime[1];
                    var hours;
                    var minutes;
                    var seconds;
                    if (time) {
                        hours = time.substr(0, 2);
                        minutes = time.substr(3, 2);
                        seconds = time.substr(6, 2);
                    }
                    return new Date(years, months, days, hours, minutes, seconds);
                }
            }
        }

        function bl_SortByDate(bl1, bl2) {
            if (bl1 && bl2) {
                var d1 = bl1[0] == 's' ? getDateObject(bl1[9]) : getDateObject(bl1[8]);
                var d2 = bl2[0] == 's' ? getDateObject(bl2[9]) : getDateObject(bl2[8]);
                return d2 > d1;
            }
        }

        function _getPointDisplay(point) {
            return !isNaN(point) ? ':' + point : '';
        }

        function _getHomeAwayScore(home, away) {
            return ' @ ' + home + ' - ' + away;
        }

        function _getOddsOption(option, marketId) {
            if (isNaN(option) || marketId == 15) {
                return option;
            } else {
                var optionId = parseInt(option);
                if (_oe[optionId]) {
                    return _oe[optionId][1];
                }
                return option;
            }
        }

        function _setCoolDown() {
            _syn.cooldownCount = 3;
            _syn.refreshCount = _syn.refreshRate;
        }

        function _drawRefreshButtons() {
            var refreshBtn = _target['refresh-button'];
            if (!refreshBtn) {
                _target['refresh-button'] = document.getElementById('bl:refresh-count');
                refreshBtn = _target['refresh-button'];
            }
            if (refreshBtn) {
                if (_ocache && _ocache.length > 0 || !_syn.initiated) {
                    refreshBtn.innerHTML = _createRefreshButton();
                } else {
                    refreshBtn.innerHTML = '';
                }
            }
        }

        function _createRefreshButton() {
            var tspanr = (_syn.cooldownCount) ? _template['refresh-text-wait'] : _template['refresh-text'];
            var refresh = tspanr.getText({
                'count': _syn.refreshCount
            });
            var button = _template['refresh-button'].getText({
                'refresh-text': refresh
            });
            return button;
        }
    }
    (function () {
        window._nox_highlights = {
            isStop: 0,
            percent: 0,
            idx: 0,
            isTimerStarted: false,
            hlData: [],
            eTimer: null,
            selectedImage: function () {
                var hl = _nox_highlights;
                var links = document.getElementById("smallImage").children;
                for (i = 0; i < links.length; ++i) {
                    var imgNum = 0 + i;
                    if (hl.idx == imgNum) {
                        links.item(i).className = "Sel";
                    } else {
                        links.item(i).className = "";
                    }
                }
            },
            imgClick: function (num) {
                var hl = _nox_highlights;
                document.getElementById("bigImg").style.display = "none";
                hl.displayData(num);
                hl.idx = num;
                hl.selectedImage();
                hl.barClear();
            },
            displayData: function (seqNo) {
                var hl = _nox_highlights;
                var article = hl.hlData[seqNo];
                if (article == null) return;
                document.getElementById("smallImage").style.display = "block";
                document.getElementById("panelMain").style.display = "block";
                document.getElementById("content").innerHTML = article.content;
                document.getElementById("artcleTitle").innerHTML = article.titleLink;
                document.getElementById("bigPic").innerHTML = article.imgLink;
                document.getElementById("bigImg").style.display = "block";
                document.getElementById("betType").innerHTML = article.bettype;
                document.getElementById("bigImg").onmouseover = function () {
                    hl.isStop = 1;
                };
                document.getElementById("bigImg").onmouseout = function () {
                    hl.isStop = 0;
                };
                document.getElementById("hgtContent").onmouseover = function () {
                    hl.isStop = 1;
                };
                document.getElementById("hgtContent").onmouseout = function () {
                    hl.isStop = 0;
                };
            },
            onTimeout: function () {
                var hl = _nox_highlights;
                hl.imgClick((hl.idx + 1) % hl.hlData.count);
            },
            increasePercent: function () {
                var hl = _nox_highlights;
                var elem = document.getElementById("divProgressbar");
                if (hl.isStop == 0 && elem) {
                    if (hl.percent >= 98) {
                        hl.onTimeout();
                        hl.percent = 0;
                        elem.style.backgroundPosition = "-290px 0px";
                    } else {
                        hl.percent += 0.2;
                        elem.style.backgroundPosition = parseInt(((hl.percent * 290) / 100) - 290) + "px 0px";
                    }
                }
                if (elem) {
                    setTimeout(hl.increasePercent, 20);
                }
            },
            barClear: function () {
                _nox_highlights.percent = 0;
            },
            reload: function (isReset) {
                var hl = _nox_highlights;
                if (typeof (document.getElementById("_nox_count")) != "undefined" && document.getElementById("_nox_count") != null) {
                    var count = parseInt(document.getElementById("_nox_count").innerHTML);
                    var hlData = hl.hlData;
                    hlData.count = count;
                    if (count > 0) {
                        for (var i = 0; i < count; i++) {
                            var tempTitle = document.getElementById("_nox_t" + i).innerHTML;
                            var tempContent = document.getElementById("_nox_c" + i).innerHTML;
                            var tempImgUrl = document.getElementById("_nox_img" + i).innerHTML;
                            var tempLink = document.getElementById("_nox_link" + i).innerHTML;
                            var tempBettype = document.getElementById("_nox_bt" + i).innerHTML;
                            var tempImgLink = document.getElementById("_nox_img_link" + i).innerHTML;
                            var tempTitleLink = document.getElementById("_nox_art_title_link" + i).innerHTML;
                            hlData[i] = {
                                "title": tempTitle.replace(/_tmpl/gi, ""),
                                "content": tempContent.replace(/_tmpl/gi, ""),
                                "imgUrl": tempImgUrl.replace(/_tmpl/gi, ""),
                                "link": tempLink.replace(/_tmpl/gi, ""),
                                "bettype": tempBettype.replace(/_tmpl/gi, ""),
                                "imgLink": tempImgLink.replace(/_tmpl/gi, ""),
                                "titleLink": tempTitleLink.replace(/_tmpl/gi, "")
                            };
                        }
                        if (!hl.isTimerStarted) {
                            hl.eTimer = setTimeout(hl.increasePercent, 20);
                            hl.isTimerStarted = true;
                        }
                        if (count > 1) {
                            if (isReset) {
                                hl.barClear();
                            }
                        }
                    }
                }
            },
            stop: function () {
                var hl = _nox_highlights;
                if (hl.eTimer) {
                    clearTimeout(hl.eTimer);
                }
                hl.isTimerStarted = false;
            },
            init: function () {
                var hl = _nox_highlights;
                hl.stop();
                hl.reload(false);
                if (hl.hlData.count > 0) {
                    hl.imgClick(0);
                    if (hl.hlData.count > 1) {
                        hl.isStop = 0;
                        var elem = document.getElementById("divProgressbar");
                        if (elem) {
                            elem.style.display = "block";
                            elem.style.backgroundPosition = "-290px 0px";
                            if (!hl.isTimerStarted) {
                                hl.eTimer = setTimeout(hl.increasePercent, 20);
                                hl.isTimerStarted = true;
                            }
                        }
                    }
                }
            }
        };
    })();

function __EuroModelRightPromo() {
    function _getUrl(action) {
        var sb = [];
        sb.push('/');
        sb.push($T('site').getValue('lang'));
        sb.push('/data/right-promo');
        sb.push('?act=');
        sb.push(action);
        var h = $M('euro').getHash();
        $M('euro').detectHash();
        if (h) {
            sb.push('&ex=');
            sb.push(h);
        }
        return sb.join('');
    }
    this.onLoad = function () {
        var sid = $T('od').getValue('sid');
        this.onSportChange(sid);
    }
    this.Update = function (template) {
        var elem = document.getElementById("panel-right-promo");
        if (elem) {
            elem.innerHTML = '';
            if (template) {
                elem.innerHTML = template;
            }
        }
    }
    this.onSportChange = function (sid) {
        var hashParam = '';
        if (!history.pushState) {
            hashParam = '&ha=1';
        }
        $P.sendRequest('rp', _getUrl('g&sid=' + sid + hashParam));
    }
    this.onClick = function (event) {
        if ($T('site').getValue('seo')) return true;
        if (!event) event = window.event;
        var e = event.srcElement ? event.srcElement : event.target;
        while (e) {
            var id = e.id;
            if (id) {
                var atom = id.split(':');
                var count = atom.length;
                if (count >= 3 && atom[0] == 'bu' && atom[1] == 'rp') {
                    switch (atom[2]) {
                    case 'to':
                        if (count >= 4) {
                            $M('euro').goTournament(atom[3], 1, 3);
                            return false;
                        }
                        break;
                    case 'ev':
                        if (count >= 4) {
                            $M('od').goEvent(atom[3]);
                            return false;
                        }
                        break;
                    case 'sp':
                        if (count >= 4) {
                            $M('euro').goSport(atom[3], 1, 3);
                            return false;
                        }
                        break;
                    default:
                        return false;
                        break;
                    }
                }
            }
            e = e.parentNode;
        }
        return true;
    };
}
upportCanvas = function () {
    var cv = document.createElement('canvas');
    return !!(cv.getContext && cv.getContext('2d'));
};

function snowing(obj, W, H) {
    var canvas = obj;
    var ctx = canvas.getContext("2d");
    canvas.width = W;
    canvas.height = H;
    var mp = 100;
    var particles = [];
    for (var i = 0; i < mp; i++) {
        particles.push({
            x: Math.random() * W,
            y: Math.random() * H,
            r: Math.random() * 2 + 1,
            d: Math.random() * mp
        })
    }

    function draw() {
        ctx.clearRect(0, 0, W, H);
        ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
        ctx.beginPath();
        for (var i = 0; i < mp; i++) {
            var p = particles[i];
            ctx.moveTo(p.x, p.y);
            ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true);
        }
        ctx.fill();
        update();
    }
    var angle = 0;

    function update() {
        angle += 0.01;
        for (var i = 0; i < mp; i++) {
            var p = particles[i];
            p.y += Math.cos(angle + p.d) + 1 + p.r / 2;
            p.x += Math.sin(angle) * 2;
            if (p.x > W + 5 || p.x < -5 || p.y > H) {
                if (i % 3 > 0) {
                    particles[i] = {
                        x: Math.random() * W,
                        y: -10,
                        r: p.r,
                        d: p.d
                    };
                } else {
                    if (Math.sin(angle) > 0 && p.x > W + 5) {
                        particles[i] = {
                            x: -5,
                            y: Math.random() * H,
                            r: p.r,
                            d: p.d
                        };
                    } else if (Math.sin(angle) < 0 && p.x < -5) {
                        particles[i] = {
                            x: W + 5,
                            y: Math.random() * H,
                            r: p.r,
                            d: p.d
                        };
                    }
                }
            }
        }
    }
    setInterval(draw, 50);
}